【问题标题】:how to exec() in a for loop? in C如何在 for 循环中执行()?在 C 中
【发布时间】: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() 函数之一确实令人恼火。但是,您并不是第一个严重误解某些功能做什么(以及不做什么)的人。清楚自己想要什么和做什么是成功沟通的基础。

标签: c linux command exec


【解决方案1】:

您正在寻找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);
}

【讨论】:

    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多