从C程序中执行另一个C程序

时间:2010-08-13 10:08:05

标签: c linux

如何从我的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程序(需要执行usng exec())从stdin读取输入一次并返回输出一次,这段代码工作正常。

但是如果我的C程序不止一次读取输入(不确切地知道从stdin读取输入的次数)并且多次显示输出那么这段代码就会崩溃。任何机构都可以建议如何解决这个问题吗?

实际上我的C程序逐行显示一些输出,并且根据输出我必须在stdin上提供输入,并且这个读/写的数量不是恒定的。

请解决此问题。

0 个答案:

没有答案