What is an easy way to check if any process of a given identifier is running on Linux?

In C ++, I have a resource bound to pid. Sometimes the process associated with this pid fails and a resource leak occurs.

Therefore, I am thinking of putting the pid file in a file that writes the resource as used. Then, when I go to get the resource, if I see an element that has been registered as being used, I would try to find out if the process corresponding to the pid is currently running, and if not, clear the resource leak.

I understand that there is very little chance that a new unrealized pid will now use the same number, but this is better than a leak without clearing. I have.

Alternatively, perhaps there is a better solution for this, if so, please suggest, otherwise I will continue to write pid.

Additional information: a resource is a port number for communication between a client and a server using tcp protocol. Only one client instance can use a given port number on a machine. Port numbers are taken from the range of available port numbers for use. While the client is running, it marks the port number that it uses in a special file on disk, and then clears this entry when exiting. For an abnormal exit, this is not always cleared, and the port number remains annotated as being in use when it is no longer in use.

+5
source share
5 answers

, kill(pid,0) ( , POSIX). . man 2 kill.

, waitpid , .

+4

- , PID. , , "--". .

Windows .

Linux flock .

+3

, (, ) (waitpid) , waitpid .

while(1) {
fork exec
waitpid
}
+2

, , - .

, ​​,

std::map< ProcessId, boost::shared_ptr<Resource> > map;
// `Resource` here references to some abstract resource type
// and `ProcessId` on Windows system would be basically a DWORD

( EnumProcesses call Windows) map. . YY .

, ( , - , ).

0

API, Windows, OpenProcess, , GetExitCodeProcess, STILL_ACTIVE, , , . Wait , API .

However, as other answers point out, this does not seem to be a promising way. We could give more focused advice if you provide more details of the script. What is your platform? What is a resource leak? Do you have access to the leaking application code? Can you wrap it in a high level try-catch with some cleanup? If not, maybe wait until the plaintiff finishes the allocated thread (or the dedicated process in general)? Any details you provide may help.

0
source

All Articles