Re: My way to check if a progam is already running



Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> writes:

On a sunny day (Sun, 24 Jun 2007 10:00:14 GMT) it happened Jan Panteltje
<pNaonStpealmtje@xxxxxxxxx> wrote in <f5lfbs$dkj$1@xxxxxxxxxxxxxxx>:

Seems to work:

// see man 3 lockf

#include <unistd.h>

struct passwd *userinfo;
FILE *lockfile;

/* get home directory */
userinfo = getpwuid(getuid() );
home_dir = strsave(userinfo -> pw_dir);

/* Locking code based on a suggestion by Michal Nazarewicz, but I use
lockf(), not flock() */

/* create a lockfile */
sprintf(temp, "%s/.MyProgram/lockfile", home_dir);
lockfile = fopen(temp, "w");
if(! lockfile)
{
fprintf(stderr, "MyProgram: could not create lockfile %s"
" aborting.\n", temp);

exit(1);
}

/* test if file is locked */
while(1)
{
a = lockf(fileno(lockfile), F_TEST, 0);
if(a == -1)
{
if(errno == EAGAIN) continue;

fprintf(stderr, "MyProgram: An other MyProgram is already"
" running, aborting.\n");

exit(1);
}

break;
}

/* lock the file */
while(1)
{
a = lockf(fileno(lockfile), F_TLOCK, 0);
if(a == -1)
{
if(errno == EAGAIN) continue;

perror("MyProgram: could not lock lockfile because: ");

exit(1);
}

break;
}

I don't think you need two loops. From what I understood EAGAIN means
that file is already locked (or otherwise cannot be locked):

EACCES or EAGAIN
The file is locked and F_TLOCK or F_TEST was specified, or the
operation is prohibited because the file has been memory-mapped
by another process.

In fact I haven't spotted any text saying this function ma be
interrupted by a signal, so I'd say that the following should be
enough (I may be wrong though):

#v+
if (lockf(fileno(lockfile), F_TLOCK, 0)!=0) {
fputs("MyProgram: Another instance is already running.\n", stderr);
exit(1);
}
#v-

--
Best regards, _ _
.o. | Liege of Serenly Enlightened Majesty of o' \,=./ `o
..o | Computer Science, Michal "mina86" Nazarewicz (o o)
ooo +--<mina86*tlen.pl>---<jid:mina86*chrome.pl>--ooO--(_)--Ooo--
.



Relevant Pages