The wait
system-call puts the process to sleep and waits for a child-process to end. It then fills in the argument with the exit code of the child-process (if the argument is not NULL
).
So if in the parent process you have
int status;
if (wait(&status) >= 0)
{
if (WEXITED(status))
{
/* Child process exited normally, through `return` or `exit` */
printf("Child process exited with %d status
", WEXITSTATUS(status));
}
}
And in the child process you do e.g. exit(1)
, then the above code will print
Child process exited with 1 status
Also note that it's important to wait for all child processes. Child processes that you don't wait for will be in a so-called zombie state while the parent process is still running, and once the parent process exits the child processes will be orphaned and made children of process 1.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…