我用Google搜索了答案,但我找到的所有主题似乎建议使用另一种方法来终止子进程:_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
}
答案 0 :(得分:0)
使用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;
}