我尝试获取子进程的退出状态,但始终为0。
我做错了,不是这样吗?

这是我的代码,令牌=命令数组。
谢谢

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;

}


总是:
状态= 0。

我需要改变什么?

最佳答案

您可能希望立即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);
}

关于c - wait(&status)总是返回0,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35924645/

10-11 22:53
查看更多