2014-02-18 25 views
0

我有一個程序,我想從一個子進程中排序文件中的第一列,並將輸出返回到父進程。我如何從execlp中獲取響應並打印它?以下是我迄今爲止:從execlp獲取回報()

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 

#define WRITE 1 
#define READ 0 

int main(int argc, char **argv) 
{ 
    int i, k; 
    int p1[2], p2[2]; 

    int p1[2], p2[2]; 
    pid_t childID; 

    if (pipe(p1) < 0 || pipe(p2) < 0) { 
     perror("pipe"); 
     exit(0); 
    } 

    childID = fork(); 

    if (childID < 0) {  
     perror("fork"); 
     exit(0); 
    } 
    else if (childID == 0){         
     close(p1[WRITE]); 
     close(p2[READ]); 

     dup2(p1[READ], STDIN_FILENO); 
     close(p1[READ]); 
     dup2(p2[WRITE], STDOUT_FILENO); 
     close(p2[WRITE]); 

     execlp("sort", "-k1", "-n", "temp.txt", (char *)NULL); 
     perror("exec"); 
     exit(0); 
    } 
    else {             
     //parent process 
     //Not sure how to get response from exec 


    } 
} 

回答

0

通話execlp()後,當前進程的內存映像將被換成了所謂的progame,所以你不能得到你想要通過返回值是什麼。你可以做的是讓子進程將其結果寫入其他地方,比如臨時文件或管道,父進程從這個地方讀取結果。

在正確設置管道以在父進程和子進程之間進行通信後,可以將子進程的結果寫入其stdout,並從其標準輸入讀取父進程中的結果。

事情是這樣的:

else if (childID == 0){         
    close(p1[READ]); 

    dup2(p1[WRITE], STDOUT_FILENO); 
    close(p1[WRITE]); 

    execlp("sort", "-k1", "-n", "temp.txt", (char *)NULL); 
    perror("exec"); 
    exit(0); 
} 
else {             
    close(p1[WRITE]); 

    dup2(p1[READ], STDIN_FILENO); 
    close(p1[READ]); 

    while (scanf("%ms ", &l) != EOF) { 
     printf("%s\n", l); 
     free(l); 
    } 
} 

這裏是全碼:

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 

#define WRITE 1 
#define READ 0 

int main(int argc, char **argv) 
{ 
    int p1[2]; 
    char *l; 

    pid_t childID; 

    if (pipe(p1) < 0) { 
     perror("pipe"); 
     exit(0); 
    } 

    childID = fork(); 

    if (childID < 0) {  
     perror("fork"); 
     exit(0); 
    } 
    else if (childID == 0){         
     close(p1[READ]); 

     dup2(p1[WRITE], STDOUT_FILENO); 
     close(p1[WRITE]); 

     execlp("sort", "-k1", "-n", "temp.txt", (char *)NULL); 
     perror("exec"); 
     exit(0); 
    } 
    else {             
     close(p1[WRITE]); 

     dup2(p1[READ], STDIN_FILENO); 
     close(p1[READ]); 

     while (scanf("%ms ", &l) != EOF) { 
      printf("%s\n", l); 
      free(l); 
     } 
    } 

    return 0; 
} 

和測試文件temp.txt

$ cat temp.txt 
a 
e 
b 
d 
f 
c 

試運行的結果:

$ ./a.out 
a 
b 
c 
d 
e 
f 
+0

感謝您的回覆。我如何才能寫出兒童流程的結果? – kirax

+0

@kirax請嘗試我已更新的答案中的代碼。 –

+0

謝謝!我想是什麼? – kirax