【发布时间】:2017-05-09 03:03:08
【问题描述】:
我正在尝试实现调用 exec() 函数的 cat 命令并将其输出保存在 tmp 文件中。我的问题是我知道在调用 exec() 之后任何事情都会被忽略,因此没有必要循环 exec()。
如果我有 N 个参数要传递给主程序,我如何循环 exec() 以读取所有参数?
注意:使用 system() 对我来说不是一个选择,这就是分配的方式。
现在我以一种不太优雅的方式拥有以下代码:
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <time.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/times.h>
#include <sys/wait.h>
int main( int argc,char *argv[] )
{
int fd;
char filename[] = "tmp.txt";
fd = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
dup2(fd, 2); // make stderr go to file
close(fd);
execl("/bin/cat", argv[0], argv[1], argv[2], argv[3], NULL);
return(0);
}
【问题讨论】:
-
你的意思是通过,而不是解析,对吧?
-
而
execv()应该做你想做的事。 linux.die.net/man/3/execv -
@MarkYisri,你是对的,我的拼写错误。
-
您的代码实际上看起来不错,只是您使用了错误的
exec函数。 -
“实现”和“调用/执行”之间有明显的区别。首先,为什么要使用
exec()函数之一确实令人恼火。但是,您并不是第一个严重误解某些功能做什么(以及不做什么)的人。清楚自己想要什么和做什么是成功沟通的基础。