简体   繁体   English

C,wait() 返回什么进程?

[英]C, What process returns for wait()?

Let's suppose that I wrote the following in main:假设我在 main 中写了以下内容:

int main() {
    int status;
    if ((p1 = fork()) != 0) {
        if ((p2 = fork()) != 0) {
            wait(&status);
            wait(&status);
        } else {
            processB();
        }
    }
    return 3;
}

plus:加:

int processB() {
    return 1;
}

when process p2 ends, what will be the value it saves in &status?当进程 p2 结束时,它在 &status 中保存的值是多少?

If it ended using exit(100) for example then it will return 100, but I don't know what will happen in this case?例如,如果它使用 exit(100) 结束,那么它将返回 100,但我不知道在这种情况下会发生什么?

The exit status from the process is encoded in 16 bits.进程的退出状态以 16 位编码。 The high-order 8 bits contain the return value from main() or the value passed to exit() (or one of its relatives);高 8 位包含来自main()的返回值或传递给exit()的值(或其亲属之一); the low-order 8 bits contain the signal that killed the process and a flag indicating that a core dump was created.低 8 位包含终止进程的信号和指示创建核心转储的标志。 The low order bits are zero if the process exited normally.如果进程正常退出,则低位为零。 The return value from wait() is the PID of the dead process. wait()的返回值是死进程的 PID。

Use code similar to this to print out the information in a semi-legible format:使用与此类似的代码以半可读格式打印出信息:

int corpse;
int status;
while ((corpse = wait(&status)) > 0)
    printf("PID %5d exited with status 0x%.4X\n", corpse, status);

If your program has return 3;如果你的程序有return 3; at the end of main() , then the value reported via the status pointer to wait() will be 0x0300 (768 = 3 * 256).main()结束时,通过状态指针报告给wait()的值将是0x0300 (768 = 3 * 256)。 If your program calls exit(100);如果你的程序调用exit(100); , the value returned by wait() will be 0x6400 (100 = 6 * 16 + 4). wait()返回的值将是 0x6400 (100 = 6 * 16 + 4)。 If your program is killed by an interrupt (SIGINT, 2), the value returned by wait() will be 0x0002.如果您的程序被中断 (SIGINT, 2) 杀死, wait()返回的值将是 0x0002。 (Technically, the actual values are system-dependent, but this is historically accurate and I know of no system where this is not what happens.) (从技术上讲,实际值取决于系统,但这在历史上是准确的,我知道没有任何系统不会发生这种情况。)

See also ExitCodes bigger than 255 — Possible?另请参阅大于 255 的 ExitCodes — 可能吗? . .

POSIX defines the <sys/wait.h> header with a bunch of relevant macros, such as: POSIX 用一堆相关的宏定义了<sys/wait.h> header,例如:

  • WIFEXITED
  • WEXITSTATUS
  • WIFSIGNALED
  • WTERMSIG
  • WIFSTOPPED
  • WSTOPSIG

And implementations often define a macro to detect core dumps — usually WCOREDUMP .并且实现通常定义一个宏来检测核心转储——通常是WCOREDUMP

See also the POSIX specification for wait() (which also specifies waitpid() ).另请参阅wait()的 POSIX 规范(也指定waitpid() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM