【问题标题】:Which process is getting exited and why is close(0) call followed after exit(0)退出哪个进程以及为什么在 exit(0) 之后调用 close(0)
【发布时间】: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 作为输入设备。这样子进程将表现为一个守护进程,并且不会从终端或标准输入读取任何内容。

【问题讨论】:

    标签: c process fork exit


    【解决方案1】:

    fork 在父进程中返回进程id,在子进程中返回0。主调用进程正在退出,因为pid == 0 所以if (pid) 在父进程中为真,在子进程中为假。然后孩子继续close(0)等。

    【讨论】:

    • 这就是我的想法,所以在这种情况下,父母正在退出,孩子被 init 带走,对吗?
    最近更新 更多