how to use wait in C

前端 未结 1 1749
南笙
南笙 2020-12-16 01:42

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

相关标签:
1条回答
  • 2020-12-16 02:13

    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.

    0 讨论(0)
提交回复
热议问题