js0823 js0823 - 6 months ago 29
C Question

How do I execute external program within C code in linux with arguments?

I want to execute another program within C code.
For example, I want to execute a command

./foo 1 2 3

is the program which exists in the same folder, and
1 2 3
are arguments.
program creates a file which will be used in my code.

How do I do this?


Use system():

int status = system("./foo 1 2 3");

system() will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode. man 2 wait on your linux system will list the various macros you can use to examine the status, the most interesting ones would be WIFEXITED and WEXITSTATUS

Alternatively, if you need to read foo's output to stdout, use popen().