14

I need to kill a process using the kill API. For that I need the process id of the process. I tried to get it using:

ret = system("pidof -s raj-srv");

but it is not returning the correct value. I dont want to kill the process using this:

ret = system("pkill raj");

Is there any API that could be used to get the process id?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
ravi J
  • 149
  • 1
  • 1
  • 3

5 Answers5

22

You are getting the return status of system. That's not the pid. You want something like this:

char line[LEN];
FILE *cmd = popen("pidof...", "r");

fgets(line, LEN, cmd);
pid_t pid = strtoul(line, NULL, 10);

pclose(cmd);
cnicutar
  • 178,505
  • 25
  • 365
  • 392
5

There could be multiple instances of processes running in that case , pidof returns strings of pid seperated by space .

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

main()
{
        char pidline[1024];
        char *pid;
        int i =0;
        int pidno[64];
        FILE *fp = popen("pidof bash","r");
        fgets(pidline,1024,fp);

        printf("%s",pidline);
        pid = strtok (pidline," ");
        while(pid != NULL)
                {

                        pidno[i] = atoi(pid);
                        printf("%d\n",pidno[i]);
                        pid = strtok (NULL , " ");
                        i++;
                }
     
        pclose(fp);
}
P0W
  • 46,614
  • 9
  • 72
  • 119
Alok Prasad
  • 622
  • 7
  • 12
2

The system() call doesn't return the output of pidof, it returns pidof's return code, which is zero if it succeeds.

You could consume the output of pidof using popen() instead of system(), but I'm sure there's a better way (the way pidof itself uses). Perhaps it wanders through /proc.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365
1

What is returned by the system function is the return code from the command being executed.

What you can do is something like this:

system("pidof -s raj-srv > /tmp/pid-of-raj-srv");

And then read the contents of the file /tmp/pid-of-raj-srv.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

I know it is not a fresh thread, but as I have only recently faced the same question, I will ask you. Did you see one of this:

You can use sysctl to give you the needed information without having to pass through a system( "bla, bla" ) call. It seems to be far more complicated at first, but may be worth depending on your needs.

j4x
  • 3,595
  • 3
  • 33
  • 64
  • 4
    That first link is broken. The second link says `sysctl()` isn't the thing to use for Linux, but `opendir()` and `readdir()` of `/proc` instead. – Craig McQueen Aug 26 '13 at 04:10