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?
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 waiton your Linux system) lists the various macros you can use to examine the status, the most interesting ones would beWIFEXITEDandWEXITSTATUS.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.