WEXITSTATUSって何をやってるの?

 

pid = fork();

if (pid < 0)

fatal_error("fork");

else if (pid == 0)

{

// child process

if (strchr(path, '/') == NULL)

path = search_path(path);

validate_access(path, argv[0]);

execve(path, argv, environ);

fatal_error("execve");

}

else

{

// parent process

wait(&wstatus);

return (WEXITSTATUS(wstatus));

}

親プロセスから子プロセスを作成して、waitで子プロセスの終了を待つわけだけど

return (wstatus);じゃなくて

return (WEXITSTATUS(wstatus));なのはなぜだろう。。。

 

 

{

// parent process

wait(&wstatus);

if (WIFEXITED(wstatus))

{

printf("wstatus:%x\n", wstatus);

printf("WIFEXITED(wstatus):%d\n", WIFEXITED(wstatus));

printf("親プロセス : 子プロセスは終了ステータス%dで正常終了しました\n", WEXITSTATUS(wstatus));

 

}

if (WIFSIGNALED(wstatus))

{

printf("wstatus:%x\n", wstatus);

printf("WIFSIGNALED(wstatus):%d\n", WIFSIGNALED(wstatus));

printf("親プロセス : 子プロセスはシグナル番号%dで終了しました\n",WTERMSIG(wstatus));

}

return (WEXITSTATUS(wstatus));

上記のように書き換えて子プロセスでexit(127)をしてみると、

下のように出力された。
ちなみにexit(127)はコマンドが見つからないときのエラー

 

wstatus:7f00
WIFEXITED(wstatus):1
親プロセス : 子プロセスは終了ステータス127で正常終了しました
 

wstatusの下位8ビットは終了ステータスを表す。つまり7f00の"00"は正常終了したことを表してる。

"7f"の部分はその他の情報を表していて、10進数に戻すと127なのでexit codeを表している。