Milk
Milk

Reputation: 657

Getting pid before process execution on Linux

How would I go about printing a process id before the process is actually executed? Is there a way I can get the previously executed process id and just increment?

i.e.

printf(<process id>);
execvp(process->args[0], process->args);

Upvotes: 2

Views: 1519

Answers (2)

nikeairj
nikeairj

Reputation: 173

You'll need to fork() and then run one of the exec() functions. To get the data from the child process, you'll need some form of communication between child and parent processes since fork() will create a separate copy of the parent process. In this example, I use pipe() to send data from child process to the parent process.

int fd[2] = {0, 0};
char buf[256] = {0};
int childPid = -1;

if(pipe(fd) != 0){
   printf("pipe() error\n");
   return EXIT_FAILURE;
}

pid_t pid = fork();
if(pid == 0) {
   // child process
   close(fd[0]);
   write(fd[1], getpid(), sizeof(int));
   execvp(process->args[0], process->args);
   _exit(0)
} else if(pid > 0){
   // parent process
   close(fd[1]);
   read(fd[0], &childPid, sizeof(childPid));
} else {
   printf("fork() error\n");
   return EXIT_FAILURE;
}
printf("parent pid: %d, child pid: %d\n", getpid(), childPid);
return 0;

Upvotes: 2

p_l
p_l

Reputation: 1179

exec family of syscalls preserve current PID, so just do:

if(fork() == 0) {
    printf("%d\n", getpid());
    execvp(process->args[0], process->args);
}

New PIDs are allocated on fork(2), which returns 0 to child process and child process' PID to parent.

Upvotes: 8

Related Questions