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



Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> writes:

On Fri, 22 Jun 2007 20:36:20 +0200 it happened Michal Nazarewicz
<mina86@xxxxxxx> wrote in <87wsxvvntn.fsf@xxxxxxxxxxxxxxxx>:

So as I said before, if you really insist on using this approach you
should read from pipe directly, like in:

#v+
FILE *fp = popen("pidof MyProgram", "r");
if (!fp) {
perror("popen");
exit(1);
}

a = fscanf(fp, "%*d %*d");
pclose(fp);

if (a==2) {
fputs("MyProgram: already running\n", stderr);
exit(1);
} else if (a==1) {
fputs("MyProgram: pidof error\n", stderr);
exit(1);
}
#v-


Yes that is nice, is better.

Still it may fail as described in previous post.

Well I will try to report it here if I ever start 2 instances of my
newsreader.

With the above code I think it is not possible to start two instances in
such a way that both will continue running. The worst case is that they
both will abort. (It's still a bug.)

I still don't see why you don't want to lock a file at the start and
unlock it when program terminates. It's way simpler operation:

#v+
FILE *lockfile = fopen("/path/to/lockfile", "w");
if (!lockfile) {
perror("fopen");
exit(1);
}
for (errno = 0; flock(fileno(lockfile), LOCK_EX | LOCK_NB); errno) {
if (errno!=EINTR) {
close(lockfile);
perror("flock");
exit(1);
}
}
#v-

#v+
flock(fileno(lockfile), LOCK_UN); /* not required */
fclose(lockfile);
#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--
.