Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fork and wait - how to wait for all grandchildren to finish

Tags:

c

I am working on an assignment to build a simple shell, and I'm trying to add a few features that aren't required yet, but I'm running into an issue with pipes.

Once my command is parsed, I fork a process to execute them. This process is a subroutine that will execute the command, if there is only one left, otherwise it will fork. The parent will execute the first command, the child will process the rest. Pipes are set up and work correctly.

My main process then calls wait(), and then outputs the prompt. When I execute a command like ls -la | cat, the prompt is printed before the output from cat.

I tried calling wait() once for each command that should be executed, but the first call works and all successive calls return ECHILD.

How can I force my main thread to wait until all children, including children of children, exit?

like image 303
Dan Avatar asked Oct 10 '12 15:10

Dan


2 Answers

You can't. Either make your child process wait for its children and don't exit until they've all been waited for or fork all the children from the same process.

like image 181
Art Avatar answered Sep 18 '22 11:09

Art


See this answer how to wait() for child processes: How to wait until all child processes called by fork() complete?

There is no way to wait for a grandchild; you need to implement the wait logic in each process. That way, each child will only exit after all it's children have exited (and that will then include all grandchildren recusively).

like image 20
Aaron Digulla Avatar answered Sep 22 '22 11:09

Aaron Digulla