XavierusWolf
XavierusWolf

Reputation: 129

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.

Upvotes: 6

Views: 36532

Answers (2)

xian
xian

Reputation: 323

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



int main(int argc, char* argv[])
{
    //char* arguments[] = {"cat","tricky.txt", NULL};
    char* arguments[] = {"./son1", 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(arguments[0], 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();
   }

}

/* if ./son1 returns printf() in son1 will be output by write(1 ..) in parent if son1 is in dead loop then printf() in son1 will NOT be output by write(1 ..) in parent

void main()
{
    printf( "***** son run *****\n\r" );
    return;
    while(1);
}

any idea?
*/

Upvotes: -2

kmkaplan
kmkaplan

Reputation: 18960

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

char* arguments[] = {"cat", "superabundantes.py", NULL};

Upvotes: 3

Related Questions