I know that waitpid()
is used to wait for a process to finish, but how would one use it exactly?
Here what I want to do is, create two children and wait for the first child to finish, then kill the second child before exiting.
//Create two children pid_t child1; pid_t child2; child1 = fork(); //wait for child1 to finish, then kill child2 waitpid() ... child1 { kill(child2) }
The waitpid() function allows the calling thread to obtain status information for one of its child processes. The calling thread suspends processing until status information is available for the specified child process, if the options argument is 0.
Returned value If successful, waitpid() returns a value of the process (usually a child) whose status information has been obtained. If WNOHANG was given, and if there is at least one process (usually a child) whose status information is not available, waitpid() returns 0.
Syntax of waitpid() : pid_t waitpid(pid_t pid, int *status, int options); The value of pid can be: < -1: Wait for any child process whose process group ID is equal to the absolute value of pid .
Yes, waitpid will work after the child has exited. The OS will keep a child process' entry in the process table (including exit status) around until the parent calls waitpid (or another wait -family function) or until the parent exits (at which point the status is collected by the init process).
Syntax of waitpid()
:
pid_t waitpid(pid_t pid, int *status, int options);
The value of pid
can be:
pid
.pid
.The value of options is an OR of zero or more of the following constants:
WNOHANG
: Return immediately if no child has exited.WUNTRACED
: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.WCONTINUED
: Also return if a stopped child has been resumed by delivery of SIGCONT
.For more help, use man waitpid
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With