简体   繁体   中英

How do I run another C program within my C program?

(All programs running on Linux and through command line) So I want to be able to run a compiled C program from within my own C program and then be able to read the output of that compiled C program and have my C program provide input for that program. (Also assume I only have the compiled version of the other C program). I am aware of the system() function, but I am not sure if I can use that to read what the compiled Program outputs and then provide my own input.

Running another C program within my C program is made thanks to the exec() family: https://linux.die.net/man/3/exec

And if you want to build your own Shell, check: Writing a Basic Shell .

You need to setup an inter-process communication mechanism between your two programs. There are several options to implement this:

  • Shared memory / shared files
  • Message Queues
  • Sockets
  • Pipes

You did not give a lot of background on your problem, but from your description it sounds that both your processes run in parallel and exchange data more than once. In this case, you will also have to think about synchronization issues.

A helpful introduction can be found here .

You can use system() like this:

system("executable arg1 ... > file.txt");

arg1 ... is the argument list to the executable. file.txt is the output of the executable redirected to a file. This system call can be made in a forked process. The parent program can wait on it. Synchronization tools can be used to enable concurrency if needed on the file file.txt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM