Get process ID by name
23,041
Solution 1
You can use the information in /proc
.
Here is an example.
Solution 2
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.
Author by
Mike Telson
Updated on April 22, 2020Comments
-
Mike Telson about 4 years
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 !
-
Mike Telson about 11 yearsWell ... I can't use that in a C++ program, can I ?
-
Walter about 11 yearswhat was wrong with your initial answer? This is now ugly C code (withdrew my upvote).
-
shakurov about 11 yearsWhat was wrong is the fact that pidof doesn't return the pid, it prints the pid to standard output (and returns 0 on success).
-
shakurov about 11 years@MikeTelson, you can use it, why not? The right way to do this is, of course, by reading proc (which one can learn from pidof source code. But it's definitely not 'easily usable'.
-
Mike Telson about 11 yearsYeah I can ! It didn't understood it with the first version of that answer but with the full code now I understand. Thanks ! (when I got 15 reputation i'll upvote)
-
Michael Zanetti almost 2 yearsLink is no longer active.