views:

67

answers:

2

I have an executable (no source) that I need to wrap, to make sure that it is not called more than once at a time. I immediately think of some sort of queue wrapper, but how do I actually make it so that my wrapper is called instead of the executable itself? Is there a better way to do this? The solution needs to be invisible because the users are other applications. Any information/recommendations are appreciated.

+1  A: 

If the users are other applications, you can just rename the executable (e.g. name -> name.real) and call the wrapper with the original name. To make sure that it's only called once at a time, you can use the pidof command (e.g. pidof name.real) to check if the program is running already (pidof actually gives you the PID of the running process, so that you can use stuff such as kill or whatever to send signals to it).

Oblomov
+1  A: 

Method 1: Put the executable in some location not in the standard path. Create a shell script that checks a sentinel file and, if the sentinel file is absent, executes the program, waits for the ptogram to complete, then deletes the sentinel file. If the sentinel file is present, the script will enter a loop with a short delay (1 second? How long is the standard execution of this program? Take that and half it), check the sentential file again, and so on.

Method 2: Create a separate program that does the same thing as the script, but using a system-level semaphore or lock instead. You could even simply use a read/write lock on a file. The program would do a fork() and exec() on the real program, waiting for child exit before clearing the sentinel.

jfawcett
If not carefully implemented both methods can result in race conditions (for example, if two processes check and find the sentinel file not present, and then both try to create it). Carefully choose an atomic operation, such as creating a directory at a known location, and make sure that operation succeeds.
Kaleb Pederson
Agreed, which is why I personally prefer option 2. If you attempt to create the directory, you can trap the exception and return to the wait loop. This isn't possible with option 1. The advantage of option 1 is that you don't have to do very much work to get it implemented. Oh, and don't use a file in /tmp for the sentinel. Put it someplace safe.
jfawcett