为什么子进程在unix中返回退出状态= 32512?

2024-03-14

在我的程序中,我正在执行给定的命令并获取结果(日志和退出状态)。另外,我的程序必须支持 shell 特定命令(即包含 shell 特定字符 ~(tild)、|(pipe)、* 的命令)。但当我尝试跑步时sh -c ls | wc通过我的程序在我的主目录中失败,其退出状态为 32512,也在 stderr 流中"sh: ls | wc: command not found"被打印了。

但有趣的是,该命令sh -c ls | wc如果我在 shell 中运行它,则工作正常。

问题是什么?或者更可取的是,我如何通过我的程序运行 shell 特定命令(即我应该运行哪个命令和哪个参数)?

下面的代码部分位于 fork() 之后的子部分中。它执行命令。

tokenized_command is std::vector<std::string>就我而言"sh", "-c", "ls", "|", "wc"已存储,我也尝试存储在那里"sh", "-c", "\"ls | wc\""但结果是一样的。command is char *存储完整命令行的位置。

        boost::shared_array<const char *> bargv(new const char *[tokenized_command.size() + 1]);
        const char **argv = bargv.get();
        for(int i = 0; i < tokenized_command.size(); ++i)
        {
            argv[i] = tokenized_command[i].c_str();
            printf("argv[%d]: %s\n", i, argv[i]); //trace
        }
        argv[tokenized_command.size()] = NULL;

        if(execvp(argv[0], (char * const *)argv) == -1)
        {
            fprintf(stderr, "Failed to execute command %s: %s", command, strerror(errno));
            _exit(EXIT_FAILURE);
        }

P.S.

我知道使用system(command)反而execvp可以解决我的问题。但system()等待命令完成,这对于我的程序来说还不够好。我也确信在实施中system()使用了 exec 系列函数之一,因此可以通过以下方式解决问题exec我也这样,但不知道怎么办


execvp获取可执行文件的路径以及用于启动该可执行文件的参数。它不需要 bourne shell 命令。

ls | wc是一个 bourne shell 命令(等等),由于使用了管道,它不能分解为可执行文件的路径和一些参数。这意味着它不能使用执行execvp.

使用以下命令执行 bourne shell 命令execvp, 必须执行sh并通过-c和参数的命令。

所以你想执行ls | wc using execvp.

char *const argv[] = {
    "sh",
    "-c", "ls | wc",  // Command to execute.
    NULL
};

execvp(argv[0], argv)

你显然尝试过

char *const argv[] = {
    "sh",
    "-c", "ls",  // Command to execute.
    "|",         // Stored in called sh's $0.
    "wc",        // Stored in called sh's $1.
    NULL
};

这与 bourne shell 命令相同sh -c ls '|' wc.

两者与 shell 命令有很大不同sh -c ls | wc。那将是

char *const argv[] = {
    "sh",
    "-c", "sh -c ls | wc",  // Command to execute.
    NULL
};

你似乎认为| and wc被传递到sh,但事实并非如此。|是一个特殊字符,它产生一个管道,而不是一个参数。


至于退出代码,

Bits 15-8 = Exit code.
Bit     7 = 1 if a core dump was produced.
Bits  6-0 = Signal number that killed the process.

32512 = 0x7F00

因此它不会因信号而终止,不会生成核心转储,并且会以代码 127 (0x7F) 退出。

127 的含义尚不清楚,这就是为什么它应该伴随着错误消息。您尝试执行程序ls | wc,但没有这样的程序。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么子进程在unix中返回退出状态= 32512? 的相关文章

随机推荐