2011-05-11 184 views
3

在下面的代碼片段我正在重定向ls命令的輸入wc -l。現在我也想重定向ls命令來命名文件的輸出,其作品完美的輸出「beejoutput.txt」使用下面的代碼,但它不工作。需要幫忙。寫作文件描述符

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
int main(void) 
{ 
    int pfds[2]; 
    pipe(pfds); 
    if (!fork()) 
    { 
    dup2(pfds[1],1); 
    close(pfds[0]); 
    execlp("ls", "ls",NULL); 
    } 
    else 
    { 
    FILE *outputO=fopen ("beejoutput.txt", "w"); //opening file for writing 

    dup2(pfds[0],0); 
    dup2(fileno(outputO),pfds[0]); 
    close(pfds[1]); 
    execlp("wc", "wc","-l", NULL); 
    } 

    return 0; 
} 
+0

你爲什麼要關閉工藝流程圖[1] execlp之前( 「WC」)? – weekens 2011-05-11 10:29:30

+0

由於該FD不應傳遞給wc命令。 – 2011-05-11 10:36:36

+0

@weekens:因爲我們不想寫任何東西到pipe.pfds [1]將被用來發送數據到父進程的子進程。 – mukesh 2011-05-11 10:37:39

回答

1

dup函數複製文件描述符,那就是,無論新老文件描述符指向同一個打開的文件之後。這與使單個文件描述符同時引用兩個不同文件不同。

如果你想發送相同的數據到兩個不同的目的地,你需要在不同的進程中產生兩個命令,並自己進行復制,或者產生一個「tee」命令的副本 - 無論哪種方式,你結束有三個過程。

+0

如果我只是想將數據發送到文件而不是'wc -l',那麼該怎麼辦?我無法將數據發送到單獨的文件 – mukesh 2011-05-11 10:43:59

+0

'dup2(fileno(outputO),0);'should do正確的事情。 – 2011-05-11 10:47:05

+0

@Simon:does not works ..replaced'dup2(pfds [0],0);'with'dup2(fileno(outputO),0);' – mukesh 2011-05-11 10:59:03

0

嘗試檢查您所做的所有系統調用(包括dup2)的結果代碼。這可能會導致你回答。無論如何,這是一個好習慣。

1

這爲我工作:

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

int main(void) 
{ 
    int pfds[2]; 
    pipe(pfds); 

    pid_t childpid = fork(); 

    if (childpid == 0) { 
     /* Child */ 
     dup2(pfds[1],1); 
     close(pfds[0]); 

     execlp("ls", "ls",NULL); 

    } else { 
     /* Parent */ 

     pid_t retpid; 
     int child_stat; 
     while ((retpid = waitpid(childpid, &child_stat, 0)) != childpid && retpid != (pid_t) -1) 
      ; 

     close(pfds[1]); 

     char buf[100]; 
     ssize_t bytesread; 

     int fd = open("beejoutput.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); 
     if (fd == -1) { 
      fprintf(stderr, "Opening of beejoutput.txt failed!\n"); 
      exit(1); 
     } 

     /* This part writes to beejoutput.txt */ 
     while ((bytesread = read(pfds[0], buf, 100)) > 0) { 
      write(fd, buf, bytesread); 
     } 

     lseek(fd, (off_t) 0, SEEK_SET); 
     dup2(fd, 0); 
     execlp("wc", "wc", "-l", NULL); 
    } 

    return 0; 
}