2011-05-11 179 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; 
}