Re: Two instances
- Posted by ghaberek (admin) Dec 24, 2012
- 1120 views
DonCole said...
How long would I keep it open?
I know until the second file has attempted to open.
When I try to open two it is usally a mistake.
And I may not aware it.
Don,
PID files are probably the most universal way to ensure a single instance of your application. Here is a good StackOverflow post on the topic: Reference for proper handling of PID file on Unix. On Windows, you could use the TEMP path (e.g. getenv("TEMP")) in place of /var/run. If you are using Win32Lib, a call to setAppName() will fail if an application with that name is already running.
Here is a quick example for using PID files.
include "std/error.e" include "std/filesys.e" include "std/io.e" -- get the proper path for storing pid files ifdef WINDOWS then constant TEMP = getenv( "TEMP" ) elsedef constant TEMP = "/var/run" -- you could also use /tmp or maybe ~/.var/run end ifdef -- build the path to our pid file sequence pid_path = join_path({ TEMP, "myapp.pid" }) -- open the pid file integer pid_file = open( pid_path, "w" ) if pid_file = -1 then crash( "Unable to create PID file!" ) end if -- lock the pid file if not lock_file( pid_file, LOCK_EXCLUSIVE ) then close( pid_file ) crash( "Unable to lock PID file!" ) end if -- write this instance id (actual pid on Linux) atom this_pid = instance() printf( pid_file, "%d\n", {this_pid} ) -- flush and unlock the file flush( pid_file ) unlock_file( pid_file ) -- do a bunch of stuff here before exiting -- close and delete the pid file close( pid_file ) delete_file( pid_path )
-Greg