Search code examples
cwait

how to use wait in C


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 pids 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);    
    }
}

Solution

  • 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 not NULL).

    So if in the parent process you have

    int status;
    if (wait(&status) >= 0)
    {
        if (WIFEXITED(status))
        {
            /* Child process exited normally, through `return` or `exit` */
            printf("Child process exited with %d status\n", WEXITSTATUS(status));
        }
    }
    

    And in the child process you do e.g. exit(1), then the above code will print

    Child process exited with 1 status
    

    Also note that it's important to wait for all child processes before the parent process ends. 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.