Preventing multiple process instances on Linux

前端 未结 5 1175
感动是毒
感动是毒 2020-12-10 17:39

What is the best way on Linux platform for the process (C++ application) to check its instance is not already running?

5条回答
  •  醉梦人生
    2020-12-10 18:29

    A related alternative to Michael's solution is to create a directory in a known location (probably under /var/run or /tmp) and use the success/failure of the system call as the mechanism for ensuring mutual exclusion. This is the same mutual-exclusion trick CVS has used for years as directory creation is atomic on most (maybe all) commodity OSes. A PID file is still useful in the case where the directory + PID creating process dies unexpectedly and fails to clean up. Additionally, when checking to see if the existing directory + PID is valid, I'd suggest explicitly checking the /proc//exe symlink to verify that it points to your executable rather than just assuming the PID hasn't been recycled.

提交回复
热议问题