【问题标题】:the return value of a child process子进程的返回值
【发布时间】:2014-08-31 07:27:14
【问题描述】:

我是forkexec 的新手,我尝试了以下程序。

方案一:

int main(int argc, char *argv[]){
    pid_t pid;
    int status;
    pid = fork();
    if(pid == 0){
        printf("new process");
        execv("p1",argv);
        }
    else{
        pid_t pr = wait(&status);// I am trying to get the exit value
                                //  of the sub process.
        printf("the child process exit with %d",status);
        printf("father still running\n");
    }
}

方案二:

int main(){
    std::cout<<"I am the new thread"<<std::endl;
    sleep(1);
    std::cout<<"after 1 second"<<std::endl;
    exit(1); 
}

我运行第一个程序,输出是“子进程以 256 退出”。为什么结果是256 而不是1?如果我把exit(1)改成exit(2),结果就变成了512,这是为什么呢?只有当我返回 0 时它才有效。

【问题讨论】:

    标签: c++ exec fork wait waitpid


    【解决方案1】:

    您从wait 系统调用返回的状态值不一定是您的子进程退出时使用的值。

    还可以返回许多其他信息,例如:

    • 进程是否正常终止?
    • 是否被信号终止?
    • 终止它的信号是什么?
    • 是否转储核心?

    为了提取退出代码,您使用宏:

    WEXITSTATUS(status)
    

    这些以及可以为您提供更多信息的宏应该可以在wait 手册页上找到,例如here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多