Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting stdout to pipe in C

Here's a program I'm trying to make:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>



int main(int argc, char* argv[])
{
    char* arguments[] = {"superabundantes.py", NULL};

    int my_pipe[2];
    if(pipe(my_pipe) == -1)
    {
        fprintf(stderr, "Error creating pipe\n");
    }

    pid_t child_id;
    child_id = fork();
    if(child_id == -1)
    {
        fprintf(stderr, "Fork error\n");
    }
    if(child_id == 0) // child process
    {
        close(my_pipe[0]); // child doesn't read
        dup2(my_pipe[1], 1); // redirect stdout

        execvp("cat", arguments);

        fprintf(stderr, "Exec failed\n");
    }
    else
    {
        close(my_pipe[1]); // parent doesn't write

        char reading_buf[1];
        while(read(my_pipe[0], reading_buf, 1) > 0)
        {
            write(1, reading_buf, 1); // 1 -> stdout
        }
        close(my_pipe[0]);
        wait();
    }
}

I want to execute the exec in the child redirecting the stdout of the child to the parent (through the pipe). I think the problem might be related to dup2, but I haven't used it before.

like image 780
XavierusWolf Avatar asked Nov 13 '22 05:11

XavierusWolf


1 Answers

You need to also provide argv[0] when you call exec. So your arguments should read:

char* arguments[] = {"cat", "superabundantes.py", NULL};
like image 138
kmkaplan Avatar answered Dec 09 '22 11:12

kmkaplan