如何在for循环中执行()?在 C
how to exec() in a for loop? in C
我正在尝试执行调用 exec() 函数并将其输出保存在 tmp 文件中的 cat 命令。我的问题是,我知道在调用 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
(标准库函数):
int execv(const char *path, char *const argv[]);
这将接受一个 argv。为了符合标准,请确保 argv[0] == path
.
所以,这是您重写的代码:
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);
execv("/bin/cat", (char *[]) { "/bin/cat", NULL });
return(0);
}
我正在尝试执行调用 exec() 函数并将其输出保存在 tmp 文件中的 cat 命令。我的问题是,我知道在调用 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
(标准库函数):
int execv(const char *path, char *const argv[]);
这将接受一个 argv。为了符合标准,请确保 argv[0] == path
.
所以,这是您重写的代码:
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);
execv("/bin/cat", (char *[]) { "/bin/cat", NULL });
return(0);
}