9

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
  • 168
  • 2
  • 9
sakthi
  • 675
  • 2
  • 10
  • 18
  • check this : http://stackoverflow.com/questions/8166415/how-to-get-the-pid-of-a-process-in-linux-in-c – Sam Daniel Jun 09 '16 at 09:22
  • Apart from the below answer other method can be writing your own kernel module and interacting with it. <-- (its lot of work but give you the id). You can also run a shell script which parses ps command and get you the pid. You can figure out more ways ..... i guess !! – sourav punoriyar Jun 09 '16 at 10:56

2 Answers2

7

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

roschach
  • 8,390
  • 14
  • 74
  • 124
Felipe Sulser
  • 1,185
  • 8
  • 19
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,277
  • 1
  • 9
  • 19