Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

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);    
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...