2010-08-13 97 views
1

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

我需要解决方案在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)从标准输入读取输入一次该代码是工作的罚款,并返回输出 一次。但如果我的C程序(需要执行usng exec)正在输入多次(不知道它会从标准输入读取输入的次数) 和显示输出放置一次(当执行显示输出行由在标准输出上) 然后这段代码崩溃了。任何机构可以建议如何解决这个问题? 其实我的C程序(需要执行usng exec)显示一些输出线,并根据输出我必须提供输入stdin 和此读/写的数量不是恒定的。

请帮我解决这个问题。

+2

/*由于数据量小,孩子可能会阻止,除非我们关闭它的输入流。这将EOF发送给 * stdin的孩子。 */ 你不这样做? – hroptatyr 2010-08-13 09:51:52

+1

请参阅http://stackoverflow.com/questions/3475682/execute-program-from-within-a-c-program 你为什么要问同样的问题两次的任何理由? – hroptatyr 2010-08-13 11:01:16

+0

詹姆斯,再次问同样的问题不会得到你的答案。您可以修改您的问题,或者询问更具体的问题以获得更好的答案,但复制相同的问题不会对您有所帮助。你可能会发现你得到了更多的回应,如果你1)保持你的问题简明扼要,2)不要在其中投入大量的代码。 – Will 2010-08-13 11:26:55

回答

1

您可以使用select api在读取/写入文件描述符时得到通知。 所以你基本上把你的读写调用放到一个循环中,然后运行select来找出外部程序何时消耗了一些字节或者写了什么给stdout。

+0

嗨Rudi, 你能为此提供一些示例代码吗?我应该使用posix线程编码等吗?如果是,请提供一些与此问题相关的示例代码。我真的无法解决这个问题 – james 2010-08-13 10:13:48

+1

@james:你的问题不是线程条件或任何其他问题,你的问题是没有循环,你做write-> read- > write-> read - > ...序列。 另外,你正在关闭你的孩子的标准输入,这意味着你的孩子的沟通渠道已经消失。 你确定你的其他程序能读取EOF吗? – hroptatyr 2010-08-13 10:55:19