Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get process ID by name

Tags:

c++

linux

process

I'd like to get a process ID given its name under Linux.

Is there a simple way to do this ?

I haven't found anything on C++ that could be easily usable !

like image 397
Mike Telson Avatar asked Mar 28 '13 15:03

Mike Telson


People also ask

How do I find the current process ID in Linux?

You can get the process ID of a process by calling getpid . The function getppid returns the process ID of the parent of the current process (this is also known as the parent process ID).


2 Answers

If going for 'easily usable',

char buf[512];
FILE *cmd_pipe = popen("pidof -s process_name", "r");

fgets(buf, 512, cmd_pipe);
pid_t pid = strtoul(buf, NULL, 10);

pclose( cmd_pipe );  

is the way to go.

Yeah, it's ugly, I know. It's much better to go and read pidof source code.

like image 117
shakurov Avatar answered Oct 04 '22 10:10

shakurov


You can use the information in /proc.

Here is an example.

like image 26
Johnny Mnemonic Avatar answered Oct 04 '22 10:10

Johnny Mnemonic