Fork in C and then pass data to Python3 program with a pipe

200 Views Asked by At

I fork in c, call a python program from child process and pass a string from parent. Now i will print this string on my python program. I have this Code:

void
forking ()
{
int thepipe[2];
char someString[] = "Hello, world!\n";
char readbuffer[80];

if (pipe (thepipe) < 0)
    {
    perror ("pipe error");
    exit (EXIT_FAILURE);
    }
pid_t pid = fork ();
if (pid < 0)
    {
    perror ("Fork failed");
    }
if (pid == 0)
    {
    close (thepipe[1]);
    execl(PYTHONPROGRAM, PYTHONPROGRAM);
    exit (0);
    }
else
    {
    close (thepipe[0]);
    write (thepipe[1], someString, (strlen (someString) + 1));
    wait (NULL);
    }
}

How can i read the pipe from the python program? I have to use os.fdopen. The code below did not work.

import os,sys
r, w = os.pipe()
os.close(w)
r = os.fdopen(r)
str = r.read()
print("text =", str)
sys.exit(0)
0

There are 0 best solutions below