execlp命令无法按我的要求打印

问题描述 投票:1回答:1

此小命令:

execlp("/bin/echo", "echo", "*", ">", "toto", 0) 

在终端中打印* > toto,但是我希望它在toto文件中打印echo *的结果。

命令:system("echo * > toto") 很好,但是我想使用execlp命令,我在做什么错呢?

谢谢你。

c unix command
1个回答
3
投票

尖括号('>')重定向特定于外壳。

例如,您可以这样做:

execlp("/bin/sh", "/bin/sh", "-c", "/bin/echo * > toto", NULL);

注意,这会调用2个与Shell相关的特定行为:

  1. *通配符:星号通配符将被扩展(由shell,非常重要)到当前目录中的所有文件;和
  2. >重定向: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是实现lsechocat和许多其他unix命令行实用程序的单个可执行文件); bash和从/bin/sh链接的任何内容肯定都是这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.