Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start a executable within a C++ program and get its process id (in linux)? [closed]

Tags:

c++

linux

i tried system(), but somehow when the secondary program runs, my main program(primary program which executes the secondary) hangs

and second issue is how do i obtain the process id of the secondary program in my main program?

like image 917
user1265478 Avatar asked Nov 26 '12 02:11

user1265478


People also ask

How do you find the PID of just started?

The two commands can be joints using ; or && . In the second case, the pid will be set only if the first command succeeds. You can get the process id from $pid . OP wants to get the PID so he can kill it later. ; and && require the original process to exit before the echo $! is executed.

How do I capture the PID of a process?

How to get PID using Task Manager. Press Ctrl+Shift+Esc on the keyboard. Go to the Processes tab. Right-click the header of the table and select PID in the context menu.


2 Answers

In the parent process you want to fork.

Fork creates an entirely new process and returns either the child process's pid to the calling process, and 0 to the new child process.

In the child process you can then use something like execl to execute your desired secondary program. In the parent process you can use waitpid to wait for the child 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;
}
like image 111
Steve Lorimer Avatar answered Oct 01 '22 07:10

Steve Lorimer


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

like image 23
Paul Beckingham Avatar answered Oct 01 '22 08:10

Paul Beckingham