Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid multiple instances of a program?

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('wmic process get caption,processid | findstr `programname.exe`')

On Linux,

os.popen('ps x | grep `programname`')

It seems to work fine for now. Is this method correct? Can someone suggest to me a better way?

edit: Thanks for the reply guys, Is anything wrong with the above methods? I tried the pid file way for linux. What if the pid file gets deleted somehow?

like image 942
asdfg Avatar asked Dec 14 '09 13:12

asdfg


People also ask

How do I stop multiple programs from running?

On most Windows computers, you can access the Task Manager by pressing Ctrl+Shift+Esc, then clicking the Startup tab. Select any program in the list and click the Disable button if you don't want it to run on startup.

How do I block multiple instances of a program in Windows 10?

Disable multiple instances of app. In order to disable multiple instances of an app on Windows 10, you need to install a free app called SingleInstance. Go ahead and download, and run the app. The app, by default, has one app pre-configured and that's the Calculator app on Windows 10.

What do you mean by multiple instances?

Multiple instances of a program mean that the program has been loaded into memory several times. (2) In object technology, a member of a class; for example, "Lassie" is an instance of the class "dog." When an instance is created, the initial values of its instance variables are assigned.


1 Answers

There are numerous ways:

  1. have an "instance file" in /var/run or similar (cross-platform)
  2. use a fixed socket (cross-platform)
  3. use DBus to register a name (linux)

What you need is a service (external to your application) that manages a namespace where unique ids are available & enforced.

like image 83
jldupont Avatar answered Sep 26 '22 06:09

jldupont