开发者

Writing to file descriptor

开发者 https://www.devze.com 2023-03-05 14:23 出处:网络
In the following snippet i am redirecting the output of the ls command to input of wc -l which works perfectly .Now i also want to redirect the output of ls command to a file named \"beejoutput.txt\"

In the following snippet i am redirecting the output of the ls command to input of wc -l which works perfectly .Now i also want to redirect the output of ls command to a file named "beejoutput.txt" using the following code but its not working. Need help.

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


The dup function duplicates a file descriptor, that is, both the old and new file descriptors refer to the same open file afterwards. That is different from having a single file descriptor refer to two different files at the same time.

If you want to send the same data to two different destinations, you need to spawn both commands in separate processes, and do the copying yourself, or spawn a copy of the "tee" command -- either way, you end up with three processes.


This worked for me :

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


Try checking the result codes of all the system calls that you do (including dup2). This will possibly lead you to an answer. This is a good habbit, anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号