C语言 如何在 C 中使用等待

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23709888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:05:29  来源:igfitidea点击:

how to use wait in C

cwait

提问by jabk

How do i use wait? It just baffles me to no end. I forka 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.

我如何使用wait?它只是让我不知所措。我fork是一棵带有递归的 procs 树,现在孩子们在运行 pstree 时必须暂停(等待/睡眠),以便我可以打印 proc 树。

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 forover them and use wait?

我应该把这个放在哪里?在父母身上if(pid > 0)还是在孩子身上if(pid==0)?也许在 ifs 的末尾,所以我将所有pids存储在数组中,然后for对它们运行 a并使用等待?

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

回答by Some programmer dude

The waitsystem-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).

wait系统调用使进程睡眠,并等待一个孩子进程结束。然后它用子进程的退出代码填充参数(如果参数不是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

在您执行的子进程中,例如exit(1),上面的代码将打印

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.

另请注意,等待所有子进程很重要。当父进程仍在运行时,您没有等待的子进程将处于所谓的僵尸状态,一旦父进程退出,子进程将被孤立并成为进程 1 的子进程。