BG Process... Need information.

Hi all,

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.

Can any one help me in how to achive this?
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).

Here's some code I wrote a while ago:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
pid_t Singleton()
{
    int semId = semget( 10000, 1, IPC_CREAT | IPC_EXCL );
    if( semId < 0 && errno == EEXIST )
    {
        semId = semget( 10000, 1, 0 );
        pid_t pid = semctl( semId, 0, GETPID );
        if( kill( pid, 0 ) >= 0 || errno != ESRCH )
            return pid;
    }

    // Perform any semaphore operation so that our PID gets stored in
    // the semaphore data structure.
    struct sembuf semops;
    semops.sem_num = 0;
    semops.sem_op  = 1;
    semops.sem_flg = 0;
    semop( semId, &semops, 1 );
    return 0;
}


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.
whoops... good thing the code isn't in use :)
Topic archived. No new replies allowed.