2010-08-13 67 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