Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of waitpid() in use?

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) } 
like image 889
user3063864 Avatar asked Jan 21 '14 03:01

user3063864


People also ask

What is Waitpid used for?

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.

What does Waitpid () return?

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.

How do I write Waitpid?

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 .

Can a child process call Waitpid?

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).


1 Answers

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.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of 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.

like image 84
mf_starboi_8041 Avatar answered Oct 04 '22 21:10

mf_starboi_8041