When using fork() and you call exec on a child, the new process
created by exec is still a child right?
When calling exec on the child the new process is handled by the child. The child's process is replaced by the exec call.
Does killing the parent process kills the child too?
It's possible for the child process to die when the parent process dies (at least in Linux) by having the OS send a signal, but otherwise it just lives on.
he calls wait/waitpid because if the parent process terminates first,
the child process dies and then you get partial or no output for the
ls command, is that correct?
You'd want to wait for the child process (as in the example you pointed to) so that:
a) you can correctly terminate your child process when finished
b) the child process has access to all the resources of the parent... meaning if your child has a file handle opened by the parent and the parent exits, but the child assumes that the file will be open as long as it's running, bad things will happen.
Take a look at this quick example:
First, look at the output of a process listing:
mike@linux-4puc:~> ps
PID TTY TIME CMD
18577 pts/2 00:00:00 bash
18643 pts/2 00:00:00 ps
Then run this little program:
void main()
{
if(fork()){
printf("parent print");
}
else
while(1);
printf("done");
}
Here you'll have the parent print the message "parent print" then "done". Check a "ps" listing when it's done and you'll see a new process in the tree hanging out:
mike@linux-4puc:~> ps
PID TTY TIME CMD
18577 pts/2 00:00:00 bash
18673 pts/2 00:00:02 a.out
18678 pts/2 00:00:00 ps
That a.out is the child, sitting forever in the while loop while the parent terminated.