In <hN******************@news04.bloor.is.net.cable.ro gers.com> Tom St Denis <to*@securescience.net> writes:
CBFalconer wrote: Rewrite it as follows:
#include <stdlib.h>
#include "running.h"
int main(void)
{
if (!running("daemon.exe") (void)system("daemon.exe");
if (!running("gui.exe") (void)system("gui.exe");
return 0;
}
I leave it to you to write running.h and the associated
running.c. If you require assistance in that you should try a
newsgroup that deals with your particular system. The words
running, daemon, gui are not specified in the C standard.
Um, system() blocks. So even with a running() function this won't work.
system() blocks *only* if the command it executes blocks. I see no
a priori indication that either daemon.exe or gui.exe block the
command processor used to start them.
You fail it.
As usual, you're the failure in this thread.
OTOH, if a program is *designed* so that only one instance can run on a
system, the test really belongs to that program, as the user might try
to start it directly.
Chuck is also wrong when recommending another newsgroup, as long as a
portable solution is possible within the framework of the C standard,
even if not perfect: lock files.
#define LOCKFILE "/tmp/daemon.exe"
...
void unlock(void)
{
remove(LOCKFILE);
}
int main()
{
FILE *fp;
if (fopen(LOCKFILE, "r") != NULL) /* terminate on the spot */ ;
if ((fp = fopen(LOCKFILE, "w")) == NULL) /* terminate on the spot */ ;
atexit(unlock);
close(fp);
...
}
The only nonportable part of the code is the definition of the LOCKFILE
macro, as each system has its own conventions about how local files
that can be created and opened in reading mode *by any user* should
be named. The "by any user" bit is important, because the failure
to open in read mode is interpreted as inexistence of the file (the C
standard could have been a little bit more helpful by requiring fopen()
to set errno to one of a minimal set of sensible values, in case of
failure -- after all, the implementation does know why it failed).
The drawback of this solution is that it is open to a race condition, if
two instances of the program are started at the same time and both
discover the absence of the lock file at the same time and decide that it
is safe to proceed. If this possibility is scaring you, replace fopen()
by one of your OS primitives that is more flexible and can create a file
only if it doesn't already exist and report error otherwise (e.g. the
O_WRONLY | O_CREAT | O_EXCL mode of open() on POSIX systems).
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email:
Da*****@ifh.de