In Linux, we can easily use system to start subprograms. However, a disadvantage of system is that it has poor control over subprograms, which is hard to obtain even the returned values.
The following is a sample code that uses execvp to call a subroutine. The following Code provides some special instructions:
1) Folk (): a new program is generated from the main program. If folk returns 0, it is a subroutine. Otherwise, it is the current program.
2) Wait (): In the main program, you can decide whether to wait for the subprogram to return before continuing the operation. In this way, the synchronization or asynchronous processing of the subprogram results will continue to run.
3) wexitstatus: used to obtain the return value of a subroutine
4) freopen: by default, the log of the subprogram and the main program are printed in the terminal. This may not be what we want, so we need to re-import the sub-program log to another log.
5) execvp: If the function runs normally, no response is returned, indicating that the startup program has an exception. It is difficult to understand the function that does not return, because we usually say that the function will return, but if we think of this as an independent process, we can understand it.
#include <sys/types.h>#include <sys/wait.h>int callApp (char* program, char** arg_list, bool isWaiting) { pid_t child_pid; /* Duplicate this process. */ child_pid = fork (); //return child_pid; if (child_pid != 0){ /* This is the parent process. */if(isWaiting == true){ /* Wait for the child process to complete. */ int child_status; wait (&child_status); int retCode = WIFEXITED (child_status); // cout << "Finish " << program << " " << retCode << " " << WEXITSTATUS (child_status) << endl; if (retCode){ // printf ("the child process exited normally, with exit code %d\n", WEXITSTATUS (child_status)); return WEXITSTATUS(child_status); } else{ // printf ("the child process exited abnormally\n"); return -1; }} }else { /* Now execute PROGRAM, searching for it in the path. */ string fLog = _temp_path+"/subprocess_log.log"; freopen(fLog.c_str(), "w", stdout); string fErrorLog = _temp_path+"/subprocess.log"; freopen(fErrorLog.c_str(), "w", stderr); chdir(_temp_path.c_str()); int ret = execvp (program, arg_list); fclose(stdout); /* The execvp function returns only if an error occurs. */ cout << "execvp failed with error code " << ret << endl; abort(); return -1; }}
// call sample
char subProcessBin[1024] = "myBin";char* configFile = "myConfig"; char* arg_list[]= { subProcessBin, "-c", configFile, NULL };
int retCode = callApp(subProcessBin, arg_list, true);
Execvp: Call a subroutine in a program and obtain the return value.