等待(& status)始终返回0

时间:2016-03-10 18:40:19

标签: c wait

我试图获得子进程的退出状态,但总是得到0。 我做错了,是不是这样?

这是我的代码,tokens =一个命令数组。 感谢

int execute(char** tokens)
{
    pid_t pid;
    int status;

    pid = fork();

    if (pid == -1)
    {
        fprintf(stderr,"ERROR: forking child process failed\n");    
        return -1;
    }

    // Child process
    if (pid == 0)
    {
        // Command was failed
        if (execvp(*tokens, tokens) == -1)
        {
            fprintf(stderr, "%s:command not found\n", *tokens);
            return 255;
        }
    }
    else
    {
        pid = wait(&status);
        status = WEXITSTATUS(status);   
    }

    return status;

}

总是: status = 0。

我需要改变什么?

1 个答案:

答案 0 :(得分:3)

您可能希望立即 exit(255) 以确保返回正确的状态。另外wait很可能获得EINTR。此外,返回状态仅在WIFEXITED(status)时才有意义,否则您不应该依赖它:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>    


int execute(char** tokens)
{
    pid_t pid;
    int status;

    pid = fork();

    if (pid == -1)
    {
        fprintf(stderr,"ERROR: forking child process failed\n");
        return -1;
    }

    // Child process
    if (pid == 0)
    {
        // Command was failed
        if (execvp(*tokens, tokens) == -1)
        {
            fprintf(stderr, "%s: command not found\n", *tokens);
            exit(255);
        }
    }
    else {
        while (1) {
             pid = wait(&status);
             if (pid == -1) {
                 if (errno == EINTR) {
                     continue;
                 }
                 perror("wait"); 
                 exit(1);
             }

             break;
        }

        if (WIFEXITED(status)) {
            int exitcode = WEXITSTATUS(status);
            printf("%d\n", exitcode);
        }
        else {
            printf("Abnormal program termination");
        }
    }

    return status;
}

int main() {
    char *args[] = {
        "/bin/cmd_not_found",
        "Hello",
        "World!",
        0
    };
    execute(args);
}