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.

Share:
23,041
Mike Telson
Author by

Mike Telson

Updated on April 22, 2020

Comments

  • Mike Telson
    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
    Mike Telson about 11 years
    Well ... I can't use that in a C++ program, can I ?
  • Walter
    Walter about 11 years
    what was wrong with your initial answer? This is now ugly C code (withdrew my upvote).
  • shakurov
    shakurov about 11 years
    What 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
    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
    Mike Telson about 11 years
    Yeah 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
    Michael Zanetti almost 2 years
    Link is no longer active.