当 child 进程遇到等待指令时会发生什么?

What happen when a child process encounter a wait instruction?

假设我有以下代码:

int main(int argc, char *argv []) {
    pid_t pid = fork();
    if (pid > 0) {
        execv(*argv, argv); 
        }
    int state=0;
    wait(&state);
    return state;
}

child 是否只是忽略等待并跳过,因为它不是调用进程?

它将 return -1 并将 errno 设置为 ECHILD 因为 child 进程没有自己的 children等着。来自 wait(2) man page:

Return value

  • wait(): on success, returns the process ID of the terminated child; on error, -1 is returned.

  • ...

Each of these calls sets errno to an appropriate value in the case of an error.

Errors

  • ECHILD (for wait())
    The calling process does not have any unwaited-for children.

  • ...


请注意,这里的逻辑与规范相反:

if (pid > 0) {
    execv(*argv, argv); 
}

此处 parent 进程正在调用 execv()。通常是 child 在 pid == 0 时这样做,而 parent 在等待。