C system call read from stdin and write to a file

Viewed 120

I am writing a C program for this: cat file.txt | wc > wc.txt this is the code:


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{

    int fd, piped[2], pid, p2p0[2];
    pipe(piped);

    pid = fork();

    if (pid == 0)
    {
        close(1);
        dup(piped[1]);
        close(piped[1]);
        close(piped[0]);
        execl("/bin/cat", "cat", "file.txt", (char *)0);
    }

    pipe(p2p0);
    pid = fork();
    if (pid == 0)
    {
        close(0);
        dup(piped[0]);
        close(piped[1]);
        close(piped[0]);

        close(1);
        dup(p2p0[1]);
        close(p2p0[1]);
        close(p2p0[0]);
        execl("/bin/wc", "wc", (char *)0);
    }

    close(piped[1]);
    close(piped[0]);
    close(p2p0[1]);

    close(0);
    dup(p2p0[0]);
    close(p2p0[0]);

    fd = open("wc.txt", O_WRONLY | O_CREAT, 0777);
    close(1);
    dup(fd);
    close(fd);


    return 0;
}

the wc.txt file is created, but my program don't print inside wc.txt.

Can you help me?

1 Answers

The pipeline you are creating is essentially

cat file.txt | wc | true >wc.txt

that is, the output of wc is being piped to another process (your parent C program after the forks) that does nothing other than exiting with success.

What you need to do is not create the second pipe, and instead dup the fd from the open("wc.txt", ... to be wc's stdout.

Note that you also don't need the second fork -- since you don't need/want to do anything after wc, you can just do the execl("wc" ... call in the parent process and don't need a second child.

Related