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

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


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);


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);}


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.