【问题标题】:Execute program from within a C program [duplicate]从C程序中执行程序[重复]
【发布时间】:2010-08-13 09:44:34
【问题描述】:

如何从我的 C 程序中运行另一个程序,我需要能够将数据写入程序启动的 STDIN(在执行程序时我必须多次通过 stdin 提供输入)(并通过来自它的 STDOUT 的行)

我需要在 Linux 下工作的解决方案。

在浏览网络时,我发现以下代码:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

void error(char *s);
char *data = "Some input data\n";

main()
{
  int in[2], out[2], n, pid;
  char buf[255];

  /* In a pipe, xx[0] is for reading, xx[1] is for writing */
  if (pipe(in) < 0) error("pipe in");
  if (pipe(out) < 0) error("pipe out");

  if ((pid=fork()) == 0) {
    /* This is the child process */

    /* Close stdin, stdout, stderr */
    close(0);
    close(1);
    close(2);
    /* make our pipes, our new stdin,stdout and stderr */
    dup2(in[0],0);
    dup2(out[1],1);
    dup2(out[1],2);

    /* Close the other ends of the pipes that the parent will use, because if
     * we leave these open in the child, the child/parent will not get an EOF
     * when the parent/child closes their end of the pipe.
     */
    close(in[1]);
    close(out[0]);

    /* Over-write the child process with the hexdump binary */
    execl("/usr/bin/hexdump", "hexdump", "-C", (char *)NULL);
    error("Could not exec hexdump");
  }

  printf("Spawned 'hexdump -C' as a child process at pid %d\n", pid);

  /* This is the parent process */
  /* Close the pipe ends that the child uses to read from / write to so
   * the when we close the others, an EOF will be transmitted properly.
   */
  close(in[0]);
  close(out[1]);

  printf("<- %s", data);
  /* Write some data to the childs input */
  write(in[1], data, strlen(data));

  /* Because of the small amount of data, the child may block unless we
   * close it's input stream. This sends an EOF to the child on it's
   * stdin.
   */
  close(in[1]);

  /* Read back any output */
  n = read(out[0], buf, 250);
  buf[n] = 0;
  printf("-> %s",buf);
  exit(0);
}

void error(char *s)
{
  perror(s);
  exit(1);
}

但是如果我的 C 程序(需要使用 exec 执行)只从标准输入读取一次输入并返回输出,则此代码工作正常 一次。但是如果我的 C 程序(需要使用 exec 执行)不止一次地接受输入(不知道它会从标准输入读取多少次) 并显示输出不止一次(执行时在标准输出上逐行显示输出) 那么这段代码就崩溃了。任何机构都可以建议如何解决这个问题? 实际上,我的 C 程序(需要使用 exec 执行)正在逐行显示一些输出,并且根据输出,我必须在 stdin 上提供输入 并且这个读/写的数量不是恒定的。

请帮我解决这个问题。

【问题讨论】:

  • /* 由于数据量小,孩子可能会阻塞,除非我们 * 关闭它的输入流。这会在它的 * stdin 上向孩子发送一个 EOF。 */ 你不这样做怎么样?
  • stackoverflow.com/questions/3475682/… 你为什么要两次问同一个问题?
  • james,再问同样的问题不会给你答案。您可以修改您的问题或询问更具体的问题以获得更好的答复,但复制粘贴相同的问题对您没有帮助。如果您 1) 让您的问题保持简洁和简短,并且 2) 不要在其中投入大量代码,您可能会发现您会得到更多回复。

标签: c linux


【解决方案1】:

您可以使用select api 在您可以读取/写入文件描述符时获得通知。 因此,您基本上会将您的读写调用放入一个循环中,然后运行 ​​select 以找出外部程序何时消耗了一些字节或将某些内容写入标准输出。

【讨论】:

  • 嗨 Rudi,你能提供一些示例代码吗?我应该使用 posix 线程代码等吗?如果是,请提供一些与此问题相关的示例代码。我真的无法解决这个问题
  • @james:您的问题不是线程条件或任何东西,您的问题是没有循环执行 write->read->write->read->... 序列。另外,您正在关闭孩子的标准输入,这意味着您与孩子的沟通渠道已经消失。您确定您的其他程序可以读取 EOF 之外的内容吗?
猜你喜欢
  • 2010-09-09
  • 2014-06-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2014-05-29
  • 2010-10-01
  • 1970-01-01
  • 2016-10-23
相关资源
最近更新 更多