I'm developing a application which should run as a single process means,
EXE : sample.exe
usage : sample.exe [start/stop]
if we try to execute this exe n number of times, onle one instance of this exe should executed and that too as a background process.. In my region if i use sample.exe start, then if some one else also try sample.exe start, if should not allow. mean time if they use sample.exe stop, then it has to stop. I've created the program in C++ by accepting the usage as command line argument.
The typical Unix paradigm for this sort of thing is to have the application create a semaphore.
If creation fails because it already exists, then you have to ask the kernel which PID owns
the semaphore. Check if that PID is still running (kill( pid, 0 ) == ESRCH means its not).
function returns pid of other running instance if one exists or 0 if there is no other running instance.
you will also need to write the code to destroy the semaphore when your app exits cleanly (not strictly necessary, as this code will handle the case where it bombed out without destroying it).
Most Unix programs just use a PID file. The problem with semaphores is that you have to maintain a global registry of numeric "keys" (the 10000 magic number in the semget() call) that everyone agrees to. With PID files (on Solaris 10 and my Fedora system they are in /var/run) you just have to have a unique name. File creation with O_EXCL is atomic, so no two processes can create the same PID file. It's more work but its quite standard and mostly free from name collision.
jsmith: your code has a bug in that it can silently fail, allowing multiple copies to run, if semget() returns with an error other than EEXIST.