8

I am using the getpid and get the pid of current process. Now I am try to get the pid of other process using process name. How to get the other process pid?

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main(void)
{
    printf("My pid:%d\n", getpid());

    return 0;
}
vijayant
  • 158
  • 1
  • 9
sakthi
  • 645
  • 2
  • 10
  • 18

2 Answers2

6

1: The most common way, used by daemons. Store the pid number in a file/files. Then other processes can easily find them.

2: Portable way, spawn a child process to executes ps with a pipe. Then you can parse the text output and find your target process.

3: Non-portable way, parse the /proc/ filesystem

Often, 1 is combined with 2 or 3, in order to verify that the pid is correct.

Stian Skjelstad
  • 2,209
  • 1
  • 8
  • 15
6

You could use popen() with the command program pidof to get the pid of any program.

Like this:

char line[total_length];
FILE * command = popen("pidof ...","r");

fgets(line,total_length,command);

pid_t pid = strtoul(line,NULL,10);
pclose(command);

Edit:

Please see: How to get the PID of a process in Linux in C

Francesco Boi
  • 7,133
  • 10
  • 64
  • 105
Felipe Sulser
  • 1,147
  • 9
  • 19