2013-07-09 21 views
1

我有下面的代碼,我用fork來啓動我的腳本。腳本正在聽stdin。我嘗試通過管道發送數據到myscript,但scipt沒有從C獲取數據。我是否在代碼中丟失了某些內容?寫入數據到叉管不起作用

static int pfds_in[2], pfds_out[2]; 

void external_init() 
{ 
    int pid; 

    if (pipe(pfds_in) < 0) 
     return; 

    if (pipe(pfds_out) < 0) 
     return; 

    if ((pid = fork()) == -1) 
     goto error; 

    if (pid == 0) { 
     /* child */ 
     close(pfds_in[0]); 
     dup2(pfds_in[1], 1); 
     close(pfds_in[1]); 

     close(pfds_out[0]); 
     dup2(pfds_out[1], 0); 
     close(pfds_out[1]); 

     const char *argv[5]; 
     int i = 0; 
     argv[i++] = "/bin/sh"; 
     argv[i++] = fc_script; 
     argv[i++] = "--json"; 
     argv[i++] = "json_continuous_input"; 
     argv[i++] = NULL; 
     execvp(argv[0], (char **) argv); 
     exit(ESRCH); 
    } 
    close(pfds_in[1]); 
    close(pfds_out[1]); 
    return; 

error: 
    exit(EXIT_FAILURE); 
} 


static void external_write_pipe_output(const char *msg) 
{ 
    char *value = NULL; 
    int i=0, len; 
    asprintf(&value, "%s\n", msg); 
    if (write(pfds_out[0], value, strlen(value)) == -1) { 
     perror("Error occured when trying to write to the pipe"); 
    } 
    free(value); 
} 

int main() 
{ 
    external_init(); 
    external_write_pipe_output("any"); 
} 

回答

1

您與從pipe()獲得的兩個文件描述符不匹配。 pfds_in[0]用於閱讀,因此您必須在您的孩子和您使用pfds_in[1]寫入管道的父母中使用dup2(pfds_in[0], 0)

btw:你想在你的孩子中通過dup(..., 1)達到什麼目的?如果你想將孩子的標準輸出重定向到你父母的管道,你必須創建另一個管道

+0

'DUP(...,0)'標準輸出和'DUP(...,1 )'爲標準輸入看到這個[主題](http://stackoverflow.com/questions/17543589/how-to-write-to-the-pipe-fork) – MOHAMED

+0

好吧,我看起來不正確。但是你總是需要'pfds _... [0]'來複制'0'和'pfds _... [1] to dup'1' –

+0

他實際上使用了兩個管道,但是,MOHAMED switch dup2(pfds_out [1],0);到dup2(pfds_out [0],0);並寫入(pfds_out [0] ...寫入(pfds_out [1] – LostBoy

0

你已經讓你的管道混在一起了。

在孩子,你應該有:

close(pfds_in[0]); 
dup2(pfds_in[1], 1); 
close(pfds_in[1]); 

close(pfds_out[1]); 
dup2(pfds_out[0], 0); 
close(pfds_out[0]); 

而且在父:

close(pfds_in[1]); 
close(pfds_out[0]); 
+0

)並寫入管道?我必須使用:'write(pfds_out [0],...)'或'write(pfds_out [1] ],...)'? – MOHAMED

+0

write(pfds_out [1],...) – LostBoy

+0

[0]是讀取端,[1]是管道的寫入端 – ams