[英]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.