views:

461

answers:

5

In a C program (p1), how to launch a dynamically constructed command (and its arguments) that reads its standard input from p1's standard output?

Note that:

  1. A method other than this stdout --> stdin piping is also OK provided it is PORTABLE across Windows and Linux.

  2. I cannot use C++, Java, Perl, Ruby, Python, etc here.

Also, will this have a MinGW dependency for its Windows build?

REOPENED: The question below answers it for Linux, but this question wants a portable method. http://stackoverflow.com/questions/70842/execute-program-from-within-a-c-program

+3  A: 

Answered: http://stackoverflow.com/questions/70842/execute-program-from-within-a-c-program

Martin York
Hey Martin - thanks for your quick response. I intuitively know that there would be M ways one could do this in Linux and N ways in Windows. What I'm trying to ask is a portable way? fork(3) eg is not available on Windows, but then, linking in MinGW could take care of that. Don't know, hence asking.
popen is _popen() in Windows, since MS decided to rename virtually every POSIX function with a leading _. A quick search on MSDN would have told you this.
Zathrus
+2  A: 

It's not 100% clear to me what you're trying to achieve exactly to be honest.

But as I understand it, you could take a look at Boost.Process

You can do things like

 bp::child cs = p.start();
 bp::postream& os = cs.get_stdin();

And then use the os as any stream to dump stuff in the standard input of your child process.

Anyway, an awful lot can be achieved with the library w.r.t. pipe redirecting and chaining.

Pieter
Hmm, boost. An 800-pound gorilla that I will need to link and shake hands with. I will still be watching out for any overall lightweight, C responses. Thanks, though. (Note that I'm now dropping the C++ from the condition.)
+1  A: 

The linked anser (which you reject) refers to POSIX pipes. POSIX is an extension to C, which adds features missing from standard C. POSIX pipes are a good example of such a feature: they were added to POSIX because standard C does not have that functionality.

MSalters
+3  A: 

The Microsoft C runtime calls it _popen instead of popen, but it appears to have the same functionality in Windows (for console applications) and Linux.

bk1e
+1  A: 

The glib library is written in C and has implementations that are well tested on both Linux and Windows. The manual section on spawning new processes will give you information about how to start a new process and hook into its stdin and stdout handles using the g_spawn_async_with_pipes call.

Ben Combee