[英]execlp command doesn't take into account the asterisk wildcard
这个小命令:
execlp("/bin/echo", "echo", "*", ">", "toto", 0)
在终端中打印* > toto
,但我希望它在文件 toto 中打印echo *
的结果。
命令 : system("echo * > toto")
运行良好,但我想使用 execlp 命令,我做错了什么?
先感谢您。
尖括号 ('>') 重定向是特定于 shell 的。
你可以这样做,例如:
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);
请注意,您仍然会将“*”写入文件。
编辑: execlp
的第一个参数实际上是要运行的可执行文件,文件映像将替代当前正在运行的进程。 在第一个参数之后是完整的argv
数组,其中必须包含argv[0]
。 我已经编辑了上面的代码以反映这一点。 一些程序使用这个argv[0]
来改变它的个性(例如, busybox
是一个单一的可执行文件,它实现了ls
、 echo
、 cat
和许多其他 unix 命令行实用程序); bash
以及从/bin/sh
链接的任何内容肯定就是这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.