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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With