(Unix/Linux) 我如何从另一个需要输入文件的 C 程序执行 C 程序?

(Unix/Linux) How would I execute a C program from another C program that requires an input file?

在上图中,代码可以简单地从终端运行。 pipeclient 和 pipeserver 文件是 运行。 pipeclient 文件使用 < 符号将 command.txt 作为输入。

现在,如果我不想从终端 运行 管道客户端文件,而是想从 C 程序 运行,我该怎么做? exec 函数集对我有帮助吗?我如何 运行 带有来自 C 程序的 command.txt 输入文件的管道客户端文件?

您可以使用 system 函数为第一个 c 调用第二个程序 program.like

1st.c

#include <stdio.h>
#include<ctype.h>
#include <stdlib.h>
int main()
{
    printf("I m 1st program");
    system("./2nd.out\n");
}

2nd.c

#include <stdio.h>
#include<ctype.h>
#include <stdlib.h>


int main(int argc, char **argv)
{
        printf("Hello there i m 2nd program\n")

}

运行 从文件获取输入的程序的低级方法是:

  • 使用open
  • 打开文件进行阅读
  • 使用 dup2 系统调用将打开的文件句柄复制到标准输入句柄之上(始终句柄 0
  • close 旧句柄(复制在句柄 0 顶部的副本将保持打开状态)
  • 使用 execveexec 系列中的另一个函数切换到新程序,该程序现在将其标准输入打开到文件。

这与 shell 本身实现 < file 输入重定向的方式相同。

这是一个 运行s /usr/bin/rev 使用来自当前目录中的 commands.txt 文件的输入的示例:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

extern char **environ;

#define ERROR(msg) do { perror(msg); exit(1); } while(0)

int main()
{
    // open the input file
    int fd = open("commands.txt", O_RDONLY);
    if (fd == -1)
        ERROR("open");

    // "dup" the handle to standard input (handle 0)
    if (dup2(fd, 0) == -1)
        ERROR("dup2");

    // close the old handle
    close(fd);

    // exec the program
    char *args[] = {"rev", NULL};
    execve("/usr/bin/rev", args, environ);

    // the program never gets here, unless the exec fails
    ERROR("execve");
    return -1;
}

您还可以使用 system 命令执行 shell 命令,包括重定向,因此程序:

#include <stdio.h>
#include <stdlib.h>

#define ERROR(msg) do { perror(msg); exit(1); } while(0)

int main()
{
    if (system("/usr/bin/rev <commands.txt"))
        ERROR("system");

    // this *will* return after completion
    return 0;
}

也可以。在这里,system 调用实际上是调用 shell(“/bin/sh”)的副本来处理命令行,就好像它是 shell 命令一样。

这样更方便,但您对调用子程序的过程(例如,设置其环境、清理其参数列表等)的控制较少。使用 system 也存在复杂的潜在安全问题,如果您的程序将 运行 作为 root,这可能是一个问题,尽管这在此处可能不是问题。