Write to file descriptor

In the following snippet, I redirect the output of the command lsto input wc -l, which works fine. Now I also want to redirect the output of the command lsto a file named "beejoutput.txt" using the following code, but it doesn’t work. Help is needed.

#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
source share
3 answers

The function dupduplicates the file descriptor, that is, both old and new file descriptors subsequently refer to the same open file. This is different from the fact that one file descriptor refers to two different files at the same time.

, "tee" - , .

+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;
}
+1

Try checking the result codes of all system calls you make (including dup2). This may lead to an answer. In any case, this is a good habit.

0
source

All Articles