I am working with a Debian (Linux like) OS writing code in c. I am a running process (let's call it "A") which needs to launch an executable program AND to get its PID when the new process "B" starts running. Both processes "A" and "B" have to remain running (i.e. neither one must terminate).
MY QUESTION: How can I make the process "A" to get the PID of process "B" once this last has been launched?
I tried to do it by using fork and execlp c functions. But the most I obtained is the PID of the child process, which is not the PID of process "B". The test code I used fro this is shown here:
int main() {
pid_t child_pid = fork();
if (child_pid == 0) {
// Child process
char *program_name = "my/Path"; // Path
char *arguments[] = {"Process_B", NULL}; // Program to be launched
if (execlp(program_name, arguments[0], NULL) == -1) {
perror("execlp_error");
return 1;
}
} else if (child_pid > 0) {
// Parent process
printf("Parent process (PID: %d) launched child with PID: %d\n", getpid(), child_pid);
} else {
perror("fork_error");
return 1;
}
return 0;
}
An example code will be highly appreciated.
I tried to do it by using fork and execlp c functions. But the most I obtained is the PID of the child process, which is not the PID of process "B".
False.
When you call the execlp
function from the child process, the program contained in program_name
replaces the program running in the child process.
So the process ID returned from fork
in the parent process is the PID of process B.
As an example, given the following code for program B:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
printf("in process B, argv[0]={{%s}}, pid=%d\n", argv[0], getpid());
return 0;
}
Running program A outputs the following:
Parent process (PID: 3292) launched child with PID: 3293
in process B, argv[0]={{Process_B}}, pid=3293