繁体   English   中英

有关子进程终止的更多信息?

[英]More Information on Child Process Termination?

我用谷歌搜索了答案,但是发现的所有线程似乎都建议使用另一种方式终止子进程:_Exit()函数。

我想知道是否使用“ return 0;”。 真正终止子进程? 我在程序中测试了这一点(在父进程中有waitpid()来捕获子进程的终止),它似乎工作得很好。

那么有人可以确认这个问题吗? return语句是否真的终止了像exit函数之类的进程,还是仅发送一个信号,表明在该进程实际上仍在运行时调用进程已“完成”?

预先感谢,丹

样例代码:

pid = fork()

if (pid == 0) // child process
{
   // do some operation
   return 0; // Does this terminate the child process?
}
else if (pid > 0) // parent process
{
   waitpid(pid, &status, 0);
   // do some operation
}

在main函数中使用return语句将立即终止进程并返回指定的值。 该过程完全终止。

int main (int argc, char **argv) {
    return 2;
    return 1;
}

该程序永远不会到达第二个return语句,并且将值2返回给调用方。

编辑-当分叉发生在另一个函数中时的示例

但是,如果return语句不在main函数内部,则子进程将不会终止,直到再次到达main()为止。 下面的代码将输出:

Child process will now return 2
Child process returns to parent process: 2
Parent process will now return 1

代码(在Linux上测试):

pid_t pid;

int fork_function() {
    pid = fork();
    if (pid == 0) {
        return 2;
    }
    else {
        int status;
        waitpid (pid, &status, 0); 
        printf ("Child process returns to parent process: %i\n", WEXITSTATUS(status));
    }
    return 1;
}

int main (int argc, char **argv) {
    int result = fork_function();
    if (pid == 0) {
        printf ("Child process will now return %i\n", result);
    }
    else {
        printf ("Parent process will now return %i\n", result);
    }
    return result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM