Reputation: 3442
I wondering if there is a way to prevent user to launch many time the program to avoid some problems.
when start my program with
/etc/init.d/myprog start
Next time when the user execute the same command it will not run.
Upvotes: 2
Views: 3524
Reputation: 14619
The Linux Standard Base supports a start_daemon
function that delivers this feature. Use it from your init script.
The start_daemon, killproc and pidofproc functions shall use this algorithm for determining the status and the pid(s) of the specified program. They shall read the pidfile specified or otherwise /var/run/basename.pid and use the pid(s) herein when determining whether a program is running. The method used to determine the status is implementation defined, but should allow for non-binary programs. 1 Compliant implementations may use other mechanisms besides those based on pidfiles, unless the -p pidfile option has been used. Compliant applications should not rely on such mechanisms and should always use a pidfile. When a program is stopped, it should delete its pidfile. Multiple pid(s) shall be separated by a single space in the pidfile and in the output of pidofproc.
This runs the specified program as a daemon. start_daemon shall check if the program is already running using the algorithm given above. If so, it shall not start another copy of the daemon unless the -f option is given. The -n option specifies a nice level. See nice(1). start_daemon should return the LSB defined exit status codes. It shall return 0 if the program has been successfully started or is running and not 0 otherwise.
Upvotes: 1
Reputation: 32923
You need to open a .lock file and lock it with flock.
int fd = open("path/to/file.lock", O_RDWR);
if (fd == -1) {
/* error opening file, abort */
}
if (flock(fd, LOCK_EX | LOCK_NB) == -1) {
/* other process already open, abort */
}
Upvotes: 1
Reputation: 70909
The best way is for the launcher to attempt a launch, capturing the pid of the launch into /var/run
Then on subsequent launches, you read the pid file, and do a process listing (ps) to see if a process with that pid is running. If so, the subsequent launch will report that the process is already running and do nothing.
Read up on pid and lock files to get an idea of what is considered standard under the init.d system.
Upvotes: 1