Preventing multiple process instances on Linux

前端 未结 5 1187
感动是毒
感动是毒 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条回答
  •  萌比男神i
    2020-12-10 18:22

    You can use files and file locks to accomplish this, but, beware it isn't perfect and don't copy the infamous Firefox bug where it refuses to start sometimes even if it isn't already running.

    The basic logic of it is:

    Invariant:
        File xxxxx will exist if and only if the program is running, and the
        contents of the file will contain the PID of that program.
    
    On startup:
        If file xxxxx exists:
            If there is a process with the PID contained in the file:
                Assume there is some instance of the program, and exit
            Else:
                Assume that the program terminated abnormally, and
                overwrite file xxxx with the PID of this program
        Else:
            Create file xxxx, and save the current PID to that file.
    
    On termination (typically registered via atexit):
        Delete file xxxxx
    

    In addition to the logic above, you should also use a second file that you lock in order to synchronize access to the PID file (i.e. to act as a mutex to make it safe in terms of process-level concurrency).

提交回复
热议问题