In some cases, a process can only generate one instance for execution. In a Unix environment, the file-and record-locking mechanisms are provided, and basic solutions for single-instance processes are provided.
Assume that a process generates a file when it starts to run, and locks the entire file, and only one of these write locks can be generated.
If the subsequent process tries to generate a write lock, it will fail. This implies that the previous instance is running.
The following method determines whether an instance is running. Every instance attempts to generate a file (/var/run/daemon. PID ). if the file is locked, the lockfile method returns an error. If the function returns 1, the process is running. If no instance is running, the program clears the file, writes the process ID, and returns 0.
The following is an implementation program:
# Include <unistd. h>
# Include <stdio. h>
# Include <stdlib. h>
# Include <fcntl. h>
# Include <syslog. h>
# Include <string. h>
# Include <errno. h>
# Include <sys/STAT. h>
# Define lockfile "/var/run/daemon. PID"
# Define lockmode (s_irusr | s_iwusr | s_irgrp | s_iroth)
Int already_running (void );
Int lockfile (INT );
Int main (INT argc, char * argv [])
{
Int val = already_running ();
If (val = 0)
{
Printf ("SART to running... \ n ");
}
Else
{
Printf ("alredy running... \ n ");
Exit (0 );
}
While (1)
{
Sleep (3 );
Printf ("... \ n ");
}
Return 0;
}
Int already_running (void)
{
Int FD;
Char Buf [16];
FD = open (lockfile, o_rdwr | o_creat, lockmode );
If (FD <0)
{
Syslog (log_err, "can't open % s: % s", lockfile, strerror (errno ));
Exit (1 );
}
If (lockfile (FD) <0)
{
If (errno = eacces | errno = eagain)
{
Close (FD );
Return 1;
}
Syslog (log_err, "can't lock % s: % s", lockfile, strerror (errno ));
Exit (1 );
}
Ftruncate (FD, 0 );
Sprintf (BUF, "% lD", (long) getpid ());
Write (FD, Buf, strlen (BUF) + 1 );
Return 0;
}
Int lockfile (int fd)
{
Struct flock FL;
Fl. l_type = f_wrlck;
Fl. l_start = 0;
Fl. l_whence = seek_set;
Fl. l_len = 0;
Return (fcntl (FD, f_setlk, & FL ));
}