用文件锁实现程序只能有一个进程实例
原理:利用文件锁,如果能加唯一写锁说明没有程序占用,否则已有进程,关闭该进程。
用途:用于需要单进程实例的程序比如守护进程。
代码示例:
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#define lockfile "OneInstance.pid"
int LockFile ( int fd) {
struct flock f1;
f1. l_type = F_WRLCK;
f1. l_start = 0 ;
f1. l_whence = SEEK_SET ;
f1. l_len = 0 ;
return fcntl ( fd, F_SETLK, & f1) ;
}
int main ( ) {
int fd;
fd = open ( lockfile, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) ;
if ( fd < 0 ) {
printf ( "can't open the lock file.\n" ) ;
exit ( 1 ) ;
}
if ( LockFile ( fd) < 0 ) {
if ( errno == EACCES || errno == EAGAIN) {
printf ( "The process only can have one instance.\n" ) ;
close ( fd) ;
return 1 ;
}
printf ( "can't lock.\n" ) ;
exit ( - 1 ) ;
}
ftruncate ( fd, 0 ) ;
char buf[ 32 ] ;
sprintf ( buf, "%ld" , ( long ) getpid ( ) ) ;
write ( fd, buf, strlen ( buf) + 1 ) ;
while ( 1 ) {
printf ( "It's the one instance process.\n" ) ;
sleep ( 1 ) ;
}
return 0 ;
}