My C program running under Linux wants to find out, by name, if another program is running. How to do it?
-
1@Mat -- "by name" means I want to issue a function call with a program name as a C-string as an argument and get a boolean return: true for yes, this named program is running; or false for no,this named program is not running. I haven't tried anything, but only googled and found nothing. I would try system( ps ) or similar but I am hoping for something much simpler and more straightforward.Pete Wilson– Pete Wilson2011-10-01 09:05:25 +00:00Commented Oct 1, 2011 at 9:05
4 Answers
There are two ways basically:
- Use
popen("pgrep yourproc", "r");and thenfgetsfrom it - Use
opendirandreaddirto parse/proc- this is basically whatps(1)does
Not the cleanest but I would go with the first of these.
5 Comments
/proc/$pid - real instructive.Travesing /proc really isn't much harder than popen(). Essentially you do 3 things
- Open all number formatted
/procentries. - Get the command invocation through
/proc/<PID>/command/ - Perform a regex match for the name of the processs you want.
I've omitted some error handling for clarity, but It should do something like what you want.
int
main()
{
regex_t number;
regex_t name;
regcomp(&number, "^[0-9]+$", 0);
regcomp(&name, "<process name>", 0);
chdir("/proc");
DIR* proc = opendir("/proc");
struct dirent *dp;
while(dp = readdir(proc)){
if(regexec(&number, dp->d_name, 0, 0, 0)==0){
chdir(dp->d_name);
char buf[4096];
int fd = open("cmdline", O_RDONLY);
buf[read(fd, buf, (sizeof buf)-1)] = '\0';
if(regexec(&name, buf, 0, 0, 0)==0)
printf("process found: %s\n", buf);
close(fd);
chdir("..");
}
}
closedir(proc);
return 0;
}
1 Comment
In unix, programs do not run. Processes run. A process can be viewed as an instance of a program. A process can operate under another name or change its name, or have no name at all. Also, at the time of running, the program can even have ceased to exits (on disk) and only exist in core. Take for instance the following program: (is /dev/null actually running? I don't think so ...)
#include <unistd.h>
#include <string.h>
int main(int arc, char **argv)
{
if (strcmp(argv[0], "/dev/null") ) {
execl( argv[0], "/dev/null", NULL );
}
sleep (30);
return 0;
}
Comments
If you want to look at the 'right' way to do this, check out the following: