how to use wait in C

2020-02-10 06:16发布

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

标签: c wait
1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-02-10 07:19

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 (WEXITED(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. 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.

查看更多
登录 后发表回答