Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the pid of another process in c?

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;
}
like image 535
sakthi Avatar asked Jun 09 '16 09:06

sakthi


People also ask

How do you find the PID of a process?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column.

Can two processes have the same PID?

Since PID is an unique identifier for a process, there's no way to have two distinct process with the same PID. Unless the processes are running in a separate PID namespaces (and thus can have the same PID).

What does getpid () do in C?

The getpid() function returns the process ID of the calling process. The getpgrp() function returns the process group ID of the calling process. The getppid() function returns the parent process ID of the calling process.


1 Answers

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.

like image 161
Stian Skjelstad Avatar answered Sep 28 '22 03:09

Stian Skjelstad