I want to execute another program within C code. For example, I want to execute a command
./foo 1 2 3
foo
is the program which exists in the same folder, and 1 2 3
are arguments.
foo
program creates a file which will be used in my code.
How do I do this?
system()
executes a shell which is then responsible for parsing the arguments and executing the desired program. To execute the program directly, use fork() and exec() (which is what system() uses to execute the shell as well as what the shell itself uses to execute commands).You can use
fork()
andsystem()
so that your program doesn't have to wait untilsystem()
returns.The
system
function invokes a shell to run the command. While this is convenient, it has well known security implications. If you can fully specify the path to the program or script that you want to execute, and you can afford losing the platform independence thatsystem
provides, then you can use anexecve
wrapper as illustrated in theexec_prog
function below to more securely execute your program.Here's how you specify the arguments in the caller:
Then call the
exec_prog
function like this:Here's the
exec_prog
function:Remember the includes:
See related SE post for situations that require communication with the executed program via file descriptors such as
stdin
andstdout
.For a simple way, use
system()
:system()
will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode:int exitcode = status / 256
).The manpage for
wait()
(in section 2,man 2 wait
on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would beWIFEXITED
andWEXITSTATUS
.Alternatively, if you need to read foo's standard output, use
popen(3)
, which returns a file pointer (FILE *
); interacting with the command's standard input/output is then the same as reading from or writing to a file.In C
In C++
Then open and read the file as usual.
Here's the way to extend to variable args when you don't have the args hard coded (although they are still technically hard coded in this example, but should be easy to figure out how to extend...):