How to run an executable file in a C ++ program and get its process identifier (on Linux)?

i tried system (), but somehow, when the secondary program starts, my main program (the main program that runs the secondary) hangs

and the second problem is how to get the process ID of the secondary program in my main program?

+6
source share
2 answers

In the parent process you want fork .

Fork creates a completely new process and returns the pid child to the calling process, and 0 to the new child.

In a child process, you can use something like execl to execute your desired secondary program. In the parent process, you can use waitpid to wait for the operation to complete.

Here is a simple illustrative example:

 #include <iostream> #include <sys/wait.h> #include <unistd.h> #include <cstdio> #include <cstdlib> int main() { std::string cmd = "/bin/ls"; // secondary program you want to run pid_t pid = fork(); // create child process int status; switch (pid) { case -1: // error perror("fork"); exit(1); case 0: // child process execl(cmd.c_str(), 0, 0); // run the command perror("execl"); // execl doesn't return unless there is a problem exit(1); default: // parent process, pid now contains the child pid while (-1 == waitpid(pid, &status, 0)); // wait for child to complete if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) { // handle error std::cerr << "process " << cmd << " (pid=" << pid << ") failed" << std::endl; } break; } return 0; } 
+11
source

Use fork to create a new process, and then exec to start the program in the new process. There are many such examples.

+4
source

All Articles