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;
}
4

3 回答 3

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;
}
于 2011-05-11T11:41:27.807 回答
1

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

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

于 2011-05-11T10:40:44.183 回答
0

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

于 2011-05-11T10:54:04.637 回答