Home > other >  pipe a buffer from my program to another program's stdin using popen
pipe a buffer from my program to another program's stdin using popen

Time:01-03

Suppose I have a program that, in part, runs another program using   FILE *outptr=popen("some command string","r")   and then fread()'s that program's stdout from outptr. Now, if that other program reads its input from its stdin, and I want that input to come from file inputfile already on disk, then I could easily just write   FILE *outptr=popen("cat inputfile|otherpgm","r");

But here's the rub: rather than some inputfile on disk, my program has an internal   unsigned char buffer[9999]   which is what I want piped to otherpgm, but which I don't want written to disk first. How can I get buffer[] piped directly to otherpgm's stdin using popen()? Or some other mechanism, as long as I can read otherpgm's stdout from within my program.

CodePudding user response:

How can I get buffer[] piped directly to otherpgm's stdin using popen()?

This can't be done using popen.

Or some other mechanism

You need to set up two pipes (see man pipe) -- one from your-program to the other-program, and one from other-program to your-program, then fork, close appropriate ends of the pipes in the child and exec other-program.

You also need to worry about deadlocks if the data you need to write or read exceeds PIPE_BUF.

Example code.

Relevant answer -- this can be much easier if you can make a FIFO on disk.

Another answer with examples.

  • Related