此小命令:
execlp("/bin/echo", "echo", "*", ">", "toto", 0)
在终端中打印* > toto
,但是我希望它在toto文件中打印echo *
的结果。
命令:system("echo * > toto")
很好,但是我想使用execlp命令,我在做什么错呢?
谢谢你。
尖括号('>')重定向特定于外壳。
例如,您可以这样做:
execlp("/bin/sh", "/bin/sh", "-c", "/bin/echo * > toto", NULL);
注意,这会调用2个与Shell相关的特定行为:
echo
命令的标准输出将重定向到文件(或管道)toto
。如果要在C中进行相同类型的重定向(即,不求助于执行Shell),则必须:
// open the file
int fd = open("toto", "w");
// reassign your file descriptor to stdout (file descriptor 1):
dup2(fd, 1); // this will first close file descriptor, if already open
// optionally close the original file descriptor (as it were duplicated in fd 1 and is not needed anymore):
close(fd);
// finally substitute the running image for another one:
execlp("/bin/echo", "echo", "*" 0);
注意,您仍然会在文件中写入'*'。
Edit: execlp
的第一个参数实际上是要运行的可执行文件,该文件图像将替代当前正在运行的进程。在第一个参数之后是完整的argv
数组,该数组必须包含argv[0]
。我已经编辑了上面的代码以反映这一点。某些程序使用此argv[0]
更改其个性(例如busybox
是实现ls
,echo
,cat
和许多其他unix命令行实用程序的单个可执行文件); bash
和从/bin/sh
链接的任何内容肯定都是这种情况。