If we type a command in a shell it basically creates a child by calling fork and then the child exec's the command we type in, so the parent of it is the shell. If it is a foreground process the parent(in this case shell) has to wait for child to terminate and if we type & it executes in the background. So what exactly makes the parent to wait or not to wait for the child to terminate?
1 Answer
As Eric Renouf commented, if you want to wait for a child process in your own code, you should use the wait
function (typically implemented as both a system call and a C library function, so you'll find manpages in both section 2 and 3). The linked page has an example implementation.
If you want to do the same thing in shell code, you can use the wait
command which waits for a backgrounded job to finish.
&
it runs in the background and doesn't wait, so what's the point you're stuck on?&
is shell syntax for running a process in the background, which means the shell will continue while the other process executes. In the foreground the shell will not do anything more (for our purposes at least) until the other process exits. If you're using the shell, just end a command with&
and it will execute in the background, you needn't do anything special. If you're writingc
code or something, if you want to block and wait for the child just callwait(3)
for the child process