Skip to content
Advertisement

Communicate with a subprocess using pipes on other than stdout/stderr

This is how I fork/exec a subprocess and communicated with it (pseudocode):

int cout_pipe[2];
pipe(cout_pipe);
fork();
if (child)
{
  dup2(cout_pipe[1],STDOUT_FILENO);
  execv();
}
if (parent)
{
  File* cout_file = fdopen(cout_pipe[0], "r");
}

My question is:

I don’t really want to read the stdout of my subprocess, I would like the subprocess to write on a file descriptor other than stdout. And, I’d like the above code to read from that file descriptor.

The subprocess is written in python, the main process in C++.

I am thinking I can change that line, from:

dup2(cout_pipe[1],STDOUT_FILENO);

To

dup2(cout_pipe[1],MY_OWN_RANDOM_FD_NUMBER);

And code the subprocess in a way that I write to MY_OWN_RANDOM_FD_NUMBER instead of stdout.

Is this a good solution? doable? How can I figure out a good MY_OWN_RANDOM_FD_NUMBER? Is there better alternatives?

Advertisement

Answer

Unless you want a specific fd, like standard out, there’s no point in the dup2. Just convert cout_pipe[1] to a string, and pass that as a command line argument to the child (in the exec). On the Python side, pick up the argument from sys.argv, convert it back to an int, and use os.fdopen to obtain a file for it.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement