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



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 user info */
userinfo = getpwuid(getuid() );

/* get home directory */
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;
}

/* No fclose()!!! file stays open, else lock is lost */

----------------------------------------------------------------------------------------
Note:
Not all systems support lockfiles, so I added a define so it uses the old method if not.
Code tested with multiple users too.



.



Relevant Pages