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



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

Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> writes:

On Fri, 22 Jun 2007 13:50:11 +0200 it happened Michal Nazarewicz
<mina86@xxxxxxx> wrote in <87y7icryx8.fsf@xxxxxxxxxxxxxxxx>:

Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> writes:

Lockfiles are bad, they show up at times as stale,
and then prevent your program to run.

/* This assumes there is a directory ~/.MyProgram/
struct passwd *userinfo;
char temp[4096];
FILE *fptr;
int a, b;

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

/* test if already a MyProgram running */
sprintf(temp, "pidof MyProgram > %s/.MyProgram/pids", home_dir);
ftr = popen(temp, "w");
pclose(ftr);

sprintf(temp, "%s/.MyProgram/pids", home_dir);
fptr = fopen(temp, "r");
if(fptr) {
a = fscanf(fptr, "%d %d", &b, &b);
fclose(fptr);
if(a == 2) {
fprintf(stderr, "MyProgram: An other MyProgram "
"is already running, aborting.\n");
exit(1);
}
}

Come to think of it it doesn't work.

I can assure you it works perfectly, I am using it.
:-)

Program testing can be used to show the presence of bugs, but never to
show their absence.
-- Edsger Wybe Dijkstra (1930-2002)

The fact that you run this code and it does what you think it does
doesn't mean that it's correct. I described a situation when you run
two instances of the program and both abort where one should continue
running and the other should abort.

Maybe even something else. Assume there is one instance running and you
run two new instances (A and B). A runs shell which truncates pids file
and executes pidof which writes two pids into pids file. Now task is
switched and B is being executed. It runs shell which truncates pids
file. Now task is switched and A opens pids file which is *empty*
(because shell executed by B truncated it) so program thinks it's the
only instance.

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.

.



Relevant Pages