I added a shortcut to an application in ubuntu. Each time i press shortcut keys, a new instance of application is created. I need only one instance, what script i can use to open the existing instance of application or creates a new one if the application is not running?
+2
A:
It depends greatly on the application. The most trivial case would be the known process name which can only be run by you (that is, no stray instances on the system):
pidof applicaton || /usr/bin/application
Opening an existing application may get tricky and, again, depends on the application. I'd suggest that you take a look at alltray thingie and pay special attention to the alltray --help
output.
Edit by ypnos: If you want to restrict this to the current user only, you should use pgrep instead of pidof, like this:
pgrep -u `id -u` application || application
Michael Krelin - hacker
2009-09-14 19:50:17
Thanks, works great.
Mehdi Sadeqi
2009-09-14 20:05:43
+1
A:
You can also try a script like this:
#! /bin/bash
user=`id -un`
lock=/tmp/$user-$1-lock
if [ -e $lock ]; then
exit #app is already running
fi
touch $lock
$@
rm $lock
If you called the script 'runner.sh', you can use it like this:
runner.sh xcalc
Is for cases where pidof doesn't work. Else go for hacker's solution, which is also more robust.
ypnos
2009-09-14 19:54:02
As much as i understand your script it ensures that only one instance of application can be running system wide even if there are many users logged on and using the same application?
Mehdi Sadeqi
2009-09-14 20:13:26
No, the lock file is bound to the user, see the variable $user in the script.
ypnos
2009-09-14 20:22:13