【发布时间】:2015-03-12 18:37:17
【问题描述】:
if (log_daemon) {
pid_t pid;
log_init();
pid = fork();
if (pid < 0) {
log_error("error starting daemon: %m");
exit(-1);
} else if (pid)
exit(0);
close(0);
open("/dev/null", O_RDWR);
dup2(0, 1);
dup2(0, 2);
setsid();
if (chdir("/") < 0) {
log_error("failed to set working dir to /: %m");
exit(-1);
}
}
我有上面的c程序,但无法弄清楚exit(0);在这种情况下做了什么,它退出了哪个进程? close(0); 的作用是什么? close(0); 会执行吗?
这段代码只是为了测试是否可以创建子进程吗?
更新: 好的,我从这个问题Start a process in the background in Linux with C得到它。
基本上,close(0); 所做的是关闭子进程的当前标准输入并打开 /dev/null 作为输入设备。这样子进程将表现为一个守护进程,并且不会从终端或标准输入读取任何内容。
【问题讨论】: