How to get the PID of a process in Linux in C
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
.