Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the PID of a process in Linux in C

Tags:

c

linux

process

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?

like image 439
ravi J Avatar asked Nov 17 '11 11:11

ravi J


2 Answers

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);
like image 122
cnicutar Avatar answered Oct 24 '22 12:10

cnicutar


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);
}
like image 30
Alok Prasad Avatar answered Oct 24 '22 14:10

Alok Prasad