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
,但没有这样的程序。