Anuj Shah
Anuj Shah

Reputation: 1

How do I make my parent wait, until a Intermediate parent, child and child of Intermediate parent finish the process using fork, wait, and waitpid?

I am creating a parent process, than an intermediate process and another child, and a child of intermediate process using fork() in C. Now I and trying to print the processes using ps -f --ppid ..,.. but some of the child processes finish hence it won't be printed when ps is ran using system(). How do I use wait and waitpid() so my parent will wait until child finishes it's process.

Current O/p:

UID PID PPID C STIME TTY TIME CMD

pc 24400 306 0 15:48 pts/2 00:00:00 ./a

pc 24401 24400 0 15:48 pts/2 00:00:00 [a]

pc 24404 24400 0 15:48 pts/2 00:00:00 sh -c ps -f --ppid 306,24400,24401,24402

Expected O/p:

UID PID PPID C STIME TTY TIME CMD

pc 24400 306 0 15:48 pts/2 00:00:00 ./a

pc 24401 24400 0 15:48 pts/2 00:00:00 ./a

pc 24402 24400 0 15:48 pts/2 00:00:00 ./a

pc 24403 24401 0 15:48 pts/2 00:00:00 ./a

pc 24404 24400 0 15:48 pts/2 00:00:00 sh -c ps -f --ppid 306,24400,24401,24402.

Thanks in advance!

Upvotes: 0

Views: 68

Answers (1)

John Bollinger
John Bollinger

Reputation: 181734

How do I use wait and waitpid() so my parent will wait until child finishes it's process.

If your intermediate process waits for its child to terminate before it terminates itself, then your initial process need only wait for each of its children.

However, a process can successfully wait() only for its own children, not their children, so if your intermediate process does not wait for its child then the wait()-family functions do not provide any mechanism by which the initial process can suspend execution until its grandchild terminates. You would need something else for that case, or to be resilient against the possibility that the intermediate process dies before it collects its child.

A relatively simple "something else" would be for the initial process to create a pipe, then launch its children, then close the write end of the pipe and try to read from the read end. The children don't need to do anything except avoid closing or writing to the write end of the pipe before they terminate -- they don't even need to be aware of the pipe. The parent's read() will block as long as any process has the write end of the pipe open.

Upvotes: 0

Related Questions