You cannot use system()
if you want to directly interact with the command you specify, since it states in the system()
description that system()
does not return until the specified command finishes: http://www.tutorialspoint.com/c_standard_library/c_function_system.htm.
As Marcelo noted, if the program you want to send data to accepts command line parametes, just specify the data on the command line you pass to system()
. Another approach if the program you want to call takes data on the stdin is to save the data to a temporary file, then specify a stdin redirect on the command line, then after system()
returns delete your file:
char *inputFileName = mkstemp("/tmp/myinputXXXXXX");
// store data in inputFileName
char buf[128];
sprintf(buf, "/path/to/myprogram < %s", inputFileName);
system(buf);
unlink(inputFileName);
If you need to interact with the program you run, you need to use another set of library functions to start the process and set up an IPC mechanism between them. The std library has a function similar to system()
which lets you do this: popen()
. popen()
lets you specify a command line similar to system()
, but it creates a pipe to the created program and returns a FILE * which lets your calling program read, write, or both, data from/to the subprocess:
FILE *myprogFP = popen("/path/to/myprog", "rw");
fprintf(myprogFP, "%d\n", i);
pclose(myprogFP);
For more information and examples of handling error returns from these functions, see for example: http://www.gnu.org/software/libc/manual/html_node/Pipe-to-a-Subprocess.html