C Programming: How to Call Another Program from Main Program?
Hi CEans, in C language, is there any possibility to call another program from main program?
To call another program from a C program, you can use the system()
function which is available in the stdlib.h
library. The system()
function executes a system shell command. It creates a shell command process, executes the command, and then returns once the command has been completed.
Here is a simple example demonstrating how to use the system()
function to call another program:
#include <stdlib.h> /* Including standard library header files */
int main() {
int return_value;
/* The system() function takes a string argument that is the command to be executed.
In this case, the command is the path to the other program that you want to run. */
return_value = system("/path/to/other/program");
/* The system() function returns an integer. This value can be used to determine if the system call was successful.
Usually, if the value is -1, it means that the system call failed. */
if(return_value == -1) {
/* Handle the error accordingly. Here, we just simply print out a message. */
printf("System call failed");
}
return 0;
}
In the above example, replace /path/to/other/program
with the path to the executable that you wish to run.
Please be aware that this is a simple example. The system()
function has limitations and potential security risks because it invokes a shell command.
The shell can interpret special characters or environment variables, potentially leading to unexpected behavior if you pass in untrusted user input.
For more controlled execution of another program, look into fork()
and exec()
functions. These functions give you more control over input, output, and error streams, and avoid invoking a shell. However, they're also more complex to use.
Also, error handling for system()
calls should be more robust in a production environment.
Error messages should be descriptive and possibly logged for troubleshooting. The error handling in this example is kept simple for demonstration purposes.