How to I check if a process is running in C? I'm trying to use ps aux |grep "process name" but failing in doing that. How do I do that?
Thanks,
How to I check if a process is running in C? I'm trying to use ps aux |grep "process name" but failing in doing that. How do I do that?
Thanks,
You may want to use pidof. This prints the pid of the running process on the stdout.
Usually its available at path /sbin/pidof; hence either you need to be the superuser or have the read access.
The command is
Your Prompt] # pidof -x <your process name>
Use as below in your C code (although not advices to use the system(<cmd>) in a C code but then you already used the same):
int
main() {
/*
** Code snippet.
*/
if(0 == system("pidof -x PROCESS > /dev/null")) {
//A process having name PROCESS is running.
}
else if(1 == system("pidof -x PROCESS > /dev/null")) {
//A process having name PROCESS is NOT running.
}
/*
** Continue processing further.
*/
return STATUS;
}
Look at the return value to decide on its running status. You can get this by executing, from the command prompt, another command 'echo $?' immediately after executing the pidof.