为什么这个程序打印一个空行?
这个程序叫做program.c. 当我运行时./program echo test,我希望程序打印test,即使命令是在子shell中运行的。为什么输出是空行?它与文件路径有关吗?当我尝试时,./program /bin/echo test我仍然得到一个空行输出。
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int function(char **argv) {
execl("/bin/bash", "sh", "-c", *argv, argv, (char*)NULL);
}
int main(int argc, char **argv) {
int return2;
function(argv + 1);
}
回答
你的程序有两个问题。
第一个问题是,argvto的论点execl()并没有像你认为的那样做。指针argv是指向 a char *(即 a char **)的指针,并且只允许将 achar *作为参数传递给execl()。也就是说,C 中的变量参数列表并不像您期望的那样工作。
为了完成您想要的,请考虑不使用execl()而使用,execv()而是传递char *您自己构造的s数组。您可以通过以下方式执行此操作,例如:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
int function(char **argv) {
// Consider passing `argc` as well to eliminate
// the need for this loop.
int len = 0;
while(argv[len]) {
len++;
}
char *new_argv[len + 3];
new_argv[0] = "sh";
new_argv[1] = "-c";
for(int i = 0; i <= len; i++) {
new_argv[i + 2] = argv[i];
}
execv("/bin/bash", new_argv);
}
int main(int argc, char **argv) {
function(argv+1);
}
但是,您仍然有一个问题:./program echo test仍然会打印一个空行,因为如果您sh -c echo test在终端中执行,您只会得到一个空行!为了解决这个问题,你需要做./program 'echo test'(对应于sh -c 'echo test'在终端),然后应该可以工作。