【发布时间】:2018-11-28 14:41:28
【问题描述】:
如果可能,我如何使用 execvp 执行以下命令:
"ls | tee ~/outputfile.txt"
我尝试运行以下代码,但收到此消息:execvp() not expected: No such file or directory 我不确定这个问题的原因, 我无法执行此命令,因为这是串联命令?
#include <unistd.h> // execvp()
#include <stdio.h> // perror()
#include <stdlib.h> // EXIT_SUCCESS, EXIT_FAILURE
int main(void) {
char *const cmd[] = {"ls | tee ~/outputfile.txt", NULL};
execvp(cmd[0], cmd);
perror("Return from execvp() not expected");
exit(EXIT_FAILURE);
}
在最后一行,想要将命令“ls”的输出写入我的代码中的文件。
提前谢谢你!
【问题讨论】:
-
*exec*()不是外壳。你可以*exec*("bash -c [whatever]")。 -
您可以使用
system()运行您的字符串。要使用execvp(),您需要解析它并创建管道并处理文件名的字扩展并进行I/O重定向。