写入文件描述符

时间:2011-05-11 10:22:42

标签: c process file-descriptor child-process dup2

在下面的代码片段中,我将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;
}

3 个答案:

答案 0 :(得分:1)

dup函数复制文件描述符,也就是说,旧文件描述符和新文件描述符之后都引用相同的打开文件。这与单个文件描述符同时引用两个不同的文件不同。

如果要将相同的数据发送到两个不同的目的地,则需要在单独的进程中生成两个命令,并自行复制,或者生成“tee”命令的副本 - 无论哪种方式,最终都会有三个过程。

答案 1 :(得分: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;
}

答案 2 :(得分:0)

尝试检查您执行的所有系统调用的结果代码(包括dup2)。这可能会引导您回答。无论如何,这是一个很好的习惯。

相关问题