View Full Version : Determaining if a program is running

04-09-2002, 02:56 AM
Okay, I know that Linux and Unix use *.pid files to determin the pid of a running program.

My question is, how would I code the creation (in c) of one of these files into my program.

The purpose of this is to check if another existance of my program in creation is running.

I know that it is possible to just create a file with some variable placed in it and go from there though, if the program is explicitly killed (ctrl C) then this file will remain existant and cause confusion amoungst those that are not aware of what is going on.
( I am aware of how to create and read files )

Any help would be good.

04-09-2002, 04:10 AM
Hmmm, okay if your using redhat, slakware etc. then try doing a "man proc" in a terminal, U should find plenty of information on the /proc filesystem. Or in other words all the current processes that are running, with this info u can determine the pid and the name of the process running, and therefore determine the existance of a duplicate program. Then just go from there.

04-09-2002, 06:03 AM
POSIX does not define how an operating system should manage processes. Linux 1.3.11 and on uses the /proc directory for process management.

If you take a look at your /proc directory, you will notice many of the subdirectories are numbered. These numbered directories correspond to processes currently running on your system. For example, if you do a 'ps' and get the PID for your current shell session, you can cd to /proc/<PID>. These subdirectories contain the information specific to the process. The virtual file 'cmdline' will give you the name (and any arguments) for the process.

Here is an example:[ /home/jdeckard ]
jdeckard@sora> ps
25308 pts/0 00:00:00 bash
25418 pts/0 00:00:00 ps

[ /home/jdeckard ]
jdeckard@sora> cd /proc/25308

[ /proc/25308 ]
jdeckard@sora> cat cmdline

You can do something similar with C, of course. Use opendir() and friends to read through /proc (check the man pages for opendir() and readdir()). Step through /proc and use atoi() to determine if you are looking at a PID subdirectory (not every subdirectory in /proc represents a PID). From there, it is a simple matter of checking the contents of the cmdline file to see if it is another instance of your own program.

You will need a way of knowing if your program is looking at itself (after all, searching through /proc will always show one instance of your program running). Use getpid() to see if your program found another instance of the program, or if it just found itself.

04-09-2002, 06:37 AM
Yeah either atoi or using regex, that works well done it myself

04-09-2002, 04:36 PM
Thanks for your help guys, I will set about implementing your ideas.