How to avoid multiple instances of a program?

前端 未结 3 484
没有蜡笔的小新
没有蜡笔的小新 2021-01-02 11:19

I need to find a right way to prevent two running instances of my (Python) program. I am currently using the following method.

On Windows,

os.popen(\         


        
3条回答
  •  离开以前
    2021-01-02 12:07

    on Linux, I used to write a pidfile, roughly:

    if (pidfile already exists)
        read pidfile content
        if (/proc//exec == my executable)
            already running, exit
        else
            it´s a stale pidfile, delete it
    write my own pid to pidfile
    start the 'real' work
    

    lately, i´ve heard of the flock(1) tool. it´s easier to use in bash scripts:

    ( flock -n 200 || exit
        # ... commands executed under lock ...
    ) 200>/var/lock/mylockfile
    

    and not too hard to use from 'real' programming languages, just open a file and try to get a flock(2) on it.

提交回复
热议问题