1

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)
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Samhamsam
  • 87
  • 9
  • You can just copy the pipe[0] file descriptor to fd 0 in the child before the exec, and then read standard input in your python program. Something like: `close(thepipe[1]); dup2(thepipe[0], 0); close(thepipe[0]); execl(PYTHONPROGRAM, PYTHONPROGRAM);`. – Ian Abbott Nov 22 '16 at 17:50
  • What do you mean with fd 0? – Samhamsam Nov 22 '16 at 18:04
  • Sorry, I meant file descriptor 0. After the `dup2(thepipe[0], 0)`, `read`s from file descriptor 0 will read from the pipe. After the `execl`, Python will get its standard input from file descriptor 0. So effectively, the Python program gets its standard input from the pipe. – Ian Abbott Nov 22 '16 at 18:11
  • Your current Python program is creating another pipe which has nothing to do with the pipe created by the parent process. – Ian Abbott Nov 22 '16 at 18:17
  • Oh ok, so i can't use fdopen then? – Samhamsam Nov 22 '16 at 18:22
  • Ok, so if i do: for line in sys.stdin: print("line") in the python file it works. – Samhamsam Nov 22 '16 at 18:32
  • You can use `fdopen` in your Python program if you know which file descriptor number corresponds to the "read" end of the pipe created before the exec, but you would probably have to pass that information via a command-line parameter (or some other means). – Ian Abbott Nov 22 '16 at 18:33

0 Answers0