linux下子進程退出狀態為什麼永遠是非正常?

#include&
#include&
#include&
using namespace std;
int main()
{
int n;
int pid;
pid = fork();
if(pid != 0)
{
cout &<&< pid &<&< endl; n = wait(NULL); if(WIFEXITED(n)) cout &<&< "normal termination exit status = " &<&< WEXITSTATUS(n) &<&< endl; else if(WIFSIGNALED(n)) cout &<&< "abnormal termination, signal number = " &<&< WTERMSIG(n) &<&< endl; } return 0; }

為什麼這段代碼輸出是abnormal termination?


囧……你認真看文檔了么……

RETURN VALUES
If wait() returns due to a stopped or terminated child process, the process ID of the child is returned to the calling process. Otherwise, a value of -1
is returned and errno is set to indicate the error.

wait 的返回值是 pid 啊,而 WIFEXITED 和 WIFSIGNALED 接受的是 status。

pid_t
wait(int *stat_loc);

WIFEXITED(status)
True if the process terminated normally by a call to _exit(2) or exit(3).

WIFSIGNALED(status)
True if the process terminated due to receipt of a signal.

就是 wait 的參數那個 status。

如你的代碼,改一下這裡就好了

n = wait(NULL);

// 改成

wait(n);

看文檔啊少年。


推薦閱讀:

LYP是一位怎樣優秀的巨巨?
為什麼C++書上的.h文件上不加預編譯語句?
C++ new分配的內存不delete會泄漏嗎?
C++ 有哪些奇技淫巧?
拷貝構造函數何時調用?

TAG:Linux | Unix | C | 進程 | UNIX環境高級編程書籍 |