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
作为输入设备。这样,子进程将充当守护进程,不会从终端或标准输入中读取任何内容。
最佳答案
fork在父进程中返回进程id,在子进程中返回0
。主调用进程正在退出,因为 pid == 0
所以 if (pid)
在父级中为 true,在子级中为 false。然后 child 继续执行 close(0)
,等等。
关于c - 退出哪个进程以及为什么在 exit(0) 之后调用 close(0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29017721/