Mike Telson
Mike Telson

Reputation: 127

Get process ID by name

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 !

Upvotes: 8

Views: 31206

Answers (1)

shakurov
shakurov

Reputation: 2518

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.

Upvotes: 9

Related Questions