This can be tricky, because you can have separate instances of the same process that live independently. For example servers listening on different ports, or services running as different users. In order to distinguish between these instances, you need to assign each of them a unique tag. The tag is often a file, but it can be a local socket in the abstract namespace, a TCP port, etc. — any unique identifier will do. When the tag is a file, it can be a regular file containing a process ID (a pidfile), or a named pipe or socket that the file is listening on, etc. Ideally, the tag is a communication endpoint that allows clients to connect to that process.
Each of these different kinds of tags results in a different way of checking whether the instance you are seeking is up and running. For example, with a local file socket, try to connect to it, and start the process if there is no process listening on that socket. If the tag is a pidfile, check if there is a process with that process ID, but beware that this is fragile, since if the process has died, there may be an unrelated process that has reused its ID. Beware that if two clients try to reach the process in a short time frame, they might both find that the process doesn't exist and both attempt to start it; properly protecting from this race condition can be tricky.
It is easier to manage instances when they are all started by the same supervisor process, and that supervisor process detects when instances die and reacts accordingly. Many service monitoring programs that can do this.
If the program doesn't respond on a known communication endpoint and it isn't managed by a supervisor program, the poor man's tag is a pidfile: a file containing the process ID. When you start the process, write the pid to a file with a prearranged name. When you need the process to exist, read the pidfile and see if there is a process with that pid. When you kill the process, erase the pidfile. The most salient problem with an unsupervised pidfile is that if the process dies, its pid may be reused by some unrelated process. You should at least check the process name or the process executable to ensure that you are talking to the right process. Many unix variants have a pgrep command: pgrep SOMENAME
lists the processes whose name contains SOMENAME as a substring, with additional options to limit to a particular user, to require an exact match, to change which of the several possible notions of “process name” is used, etc.
ps -ef | grep -v grep | grep "process_name" || run_command_here
– Rahul Patil Jun 10 '13 at 07:58pgrep "process_name"
instead ofps | grep | grep
– rush Jun 10 '13 at 09:09