使用Record Locking只启动一个进程实例。通过记录锁锁文件方式实现。
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define FILE_PATH "LockFile.txt"
#define MAXLINE 4096 /* max text line length */
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int LockSet(int fd, int Type)
{
struct flock lock;
lock.l_type = Type; /* F_RDLCK, F_WRLCK, F_UNLCK */
lock.l_start = 0; /* byte offset, relative to l_whence */
lock.l_whence = SEEK_END; /* SEEK_SET, SEEK_CUR, SEEK_END */
lock.l_len = 0; /* #bytes (0 means to EOF) */
return fcntl( fd, F_SETLK, &lock);
}
int main(int argc, char **argv)
{
char line[MAXLINE] = {0};
int fd = open(FILE_PATH, O_RDWR | O_CREAT| O_APPEND , FILE_MODE);
if ( LockSet(fd, F_WRLCK) < 0 )
{
if (errno == EACCES || errno == EAGAIN)
{
printf("This program has running!\n");
close(fd);
}
else
{
printf("call fcntl function error.%s\n", strerror(errno) );
}
exit(1);
}
printf("lock file [%s] successful\n", FILE_PATH);
snprintf(line, sizeof(line), "%ld\n", (long) getpid());
lseek(fd, 0, SEEK_END);
write(fd, line, strlen(line));
getchar();
if ( LockSet(fd, F_UNLCK) < 0 )
{
printf("call fcntl function error.%s\n", strerror(errno) );
}
close(fd);
return 0;
}
http://www.cppblog.com/Files/bujiwu/RecordLocking.rar