Hello All,
I have a program that run as a daemon. My problem seems to be simple but I didn't find the answer anywhere.
How do I alow only one instance of my program to run ?
Thanks in advance,
Hello All,
I have a program that run as a daemon. My problem seems to be simple but I didn't find the answer anywhere.
How do I alow only one instance of my program to run ?
Thanks in advance,
Hello,
I'm not certain this can be accomplished with the C or C++ standard. Rather it is OS specific. What OS will your daemon run on, and/or what compiler are you using for this project?
- Stack Overflow
Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.
I'm assuming these are Linux Daemons right?
Yes, it is running on a Linux machine and gcc version 3.3.3 !
I've create a daemon like this:
Thanks !Code:int daemon(int nochdir, int noclose) { int fd; switch (fork()) { case -1: return -1; case 0: break; default: _exit(0); } if (setsid() == -1) return -1; if (!nochdir) chdir("/"); if (noclose) return 0; fd = open(_PATH_DEVNULL, O_RDWR, 0); if (fd != -1) { dup2(fd, STDIN_FILENO); dup2(fd, STDOUT_FILENO); dup2(fd, STDERR_FILENO); if (fd > 2) close(fd); } return 0; }
Hello All,
Any help ?
Thanks again,
Here are a number of possible ways, none of them ideal.
1. Parse the output of 'ps' looking for instances of your process
Disadvantage - syntax of the ps command isn't portable.Code:FILE *fp = popen( "ps -e", "r" ); while ( fgets( buff, sizeof buff, fp ) ) { } pclose( fp );
2. create a lock file - which is typically the name of your daemon and its process ID
Eg. /tmp/mydaemon12345.lock
Cases are
- lock file missing -> not running so go ahead and be the one
- lock file present, but process 12345 doesn't exist -> previous instance died badly
- lock file present, but process 12345 isn't mydaemon -> previous instance died badly
- lock file present and process 12345 is mydaemon -> already running.
You need to make good use of atexit() and signal() to install handlers which remove the lock file in all the ways in which your program can exit (either normally or via a crash).