Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an easy way to test whether any process of a given id is presently running on Linux?

Tags:

c++

linux

In C++, I have a resource that is tied to a pid. Sometimes the process associated with that pid exits abnormally and leaks the resource.

Therefore, I'm thinking of putting the pid in the file that records the resource as being in use. Then when I go to get a resource, if I see an item as registered as being in use, I would search to see whether a process matching the pid is currently running, and if not, clean up the leaked resource.

I realize there is a very small probability that a new unrealated pid is now sharing the same number, but this is better than leaking with no clean up I have now.

Alternatively, perhaps there is a better solution for this, if so, please suggest, otherwise, I'll pursue the pid recording.

Further details: The resource is a port number for communication between a client and a server over tcp. Only one instance of the client may use a given port number on a machine. The port numbers are taken from a range of available port numbers to use. While the client is running, it notes the port number it is using in a special file on disk and then cleans this entry up on exit. For abnormal exit, this does not always get cleaned up and the port number is left annotated as being in use, when it is no longer being used.

like image 634
WilliamKF Avatar asked Jul 05 '10 18:07

WilliamKF


2 Answers

To check for existence of process with a given id, use kill(pid,0) (I assume you are on POSIX system). See man 2 kill for details.

Also, you can use waitpid call to be notified when the process finishes.

like image 63
Roman Cheplyaka Avatar answered Sep 28 '22 16:09

Roman Cheplyaka


I would recommend you use some kind of OS resource, not a PID. Mutexes, semaphores, delete-on-close files. All of these are cleaned up by the OS when a process exits.

On Windows, I would recommend a named mutex.

On Linux, I would recommend using flock on a file.

like image 40
Dark Falcon Avatar answered Sep 28 '22 17:09

Dark Falcon