How do i use wait
? It just baffles me to no end. I fork
a tree of procs with recursion and now the children have to pause(wait/sleep) while I run pstree so I can print the proc tree.
Should i use
int status;
wait(&status);
or rather
wait(NULL)
and where should i put this? in the parent if(pid > 0)
or in the children if(pid==0)
? Maybe at the end of ifs, so I store all the pid
s in array and then run a for
over them and use wait?
my code template:
void ProcRec(int index)
{
pid_t pid;
int noChild = getNChild(index);
int i= 0;
for(i = 0; i < noChild; i++)
{
pid = fork();
if (pid > 0)
{
/* parent process */
}
else if (pid == 0)
{
/* child process. */
createProc(index+1);
}
else
{
/* error */
exit(EXIT_FAILURE);
}
}
if(getpid() == root)
{
sleep(1);
pid = fork();
if(pid == 0)
execl("/usr/bin/pstree", "pstree", getppid(), 0);
}
}
The
wait
system-call puts the process to sleep and waits for a child-process to end. It then fills in the argument with the exit code of the child-process (if the argument is notNULL
).So if in the parent process you have
And in the child process you do e.g.
exit(1)
, then the above code will printAlso note that it's important to wait for all child processes. Child processes that you don't wait for will be in a so-called zombie state while the parent process is still running, and once the parent process exits the child processes will be orphaned and made children of process 1.