How should I run another program from within my C
program? I need to be able to write data into STDIN
of the launched program (and maybe read from it's STDOUT
)
I am not sure if this is a standard C function. I need the solution that should work under Linux.
I disagree with Nathan Fellman - the other question is not a duplicate of this, though the subject is related.
For simple unidirectional communication, popen() is a decent solution. It is no use for bi-directional communication, though.
IMO, imjorge (Jorge Ferreira) gave most of the answer (80%?) for bi-directional communication - but omitted a few key details.
If you do not close the unused ends of the pipes, you do not get sensible behaviour when one of the programs terminates; for example, the child might be reading from its standard input, but unless the write end of the pipe is closed in the child, it will never get EOF (zero bytes from read) because it still has the pipe open and the system thinks it might sometime get around to writing to that pipe, even though it is currently hung waiting for something to read from it.
The writing processes should consider whether to handle the SIGPIPE signal that is given when you write on a pipe where there is no reading process.
You have to be aware of pipe capacity (platform dependent, and might be as little as 4KB) and design the programs to avoid deadlock.
pipe(...)
, one forstdin
, one forstdout
.fork(...)
the process.fork(...)
returns 0)dup (...)
the pipes tostdin
/stdout
.exec[v][e]
the to be started programm file in the child process.fork
) returns the PID of the child) do a loop that reads from the child'sstdout
(select(...)
orpoll(...)
,read(...)
) into a buffer, until the child terminates (waitpid(...)
).stdin
if it expects some.close(...)
the pipes.You can use the system call, read manpage for system(3)
You want to use
popen
. It gives you a unidirectional pipe with which you can access stdin and stdout of the program.popen is standard on modern unix and unix-like OS, of which Linux is one :-)
Type
in a terminal to read more about it.
EDIT
Whether
popen
produces unidirectional or bidirectional pipes depends on the implementation. In Linux and OpenBSD,popen
produces unidirectional pipes, which are read-only or write-only. On OS X, FreeBSD and NetBSDpopen
produces bidirectional pipes.I wrote some example C code for someone else a while back that shows how to do this. Here it is for you:
I think you can use
for this .