为什么 fork() 返回值是 -1,为什么 wait() 退出状态不是 0? [英] Why is the fork() return value -1 and why is the wait() exit status not 0?

查看:56
本文介绍了为什么 fork() 返回值是 -1,为什么 wait() 退出状态不是 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在程序中:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
    int pid;
    int status;

    pid = fork();

    if (pid < 0)
    {
        return -1;
    }
    else if (pid == 0)
    {
        printf("I am the child\n");
        exit(0);
    }
    else if (pid > 0)
    {
        pid = wait(&status);
        printf("I am the parent\n");
        printf("My pid is %i\nMy childs's pid is %i\nMy childs's exit status is     %i\n", getpid(), pid, status);

    }

}

这个程序返回:

I am the child
I am the parent
My pid is 16269
My childs's pid is -1
My childs's exit status is 32767

1) 为什么子进程的 pid = -1 而不是实际的子进程号?

1) Why is the child's pid = -1 and not the actual child process number?

2) 为什么孩子的退出状态 != 0,正如我预期的那样?

2) Why is the child's exit status != 0, as I intended?

推荐答案

关于子进程id,是因为你重新赋值了pid变量,wait返回-1 出错.

Regarding the child process id, it's because you reassign the pid variable, and wait returns -1 on an error.

关于退出状态,它是无效的,因为wait失败了.但除此之外,它只是包含实际状态的最低八位.首先你需要确保wait调用确实成功了,然后你需要用WIFEXITED宏检查进程是否正常退出,然后用WEXITSTATUS 宏.

Regarding the exit status, it's invalid since wait failed. But otherwise it's only the eight lowest bits that contain the actual status. First you need to make sure that the wait call actually succeeded, then you need to check if the process exited normally with the WIFEXITED macro, and then get the actual exit status with the WEXITSTATUS macro.

我建议您阅读wait 头文件.

I suggest you read a reference for wait and the <sys/wait.h> header file.

这篇关于为什么 fork() 返回值是 -1,为什么 wait() 退出状态不是 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆