Jiwu Bu

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  32 随笔 :: 0 文章 :: 25 评论 :: 0 Trackbacks
使用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

posted on 2009-12-18 15:57 bujiwu 阅读(451) 评论(0)  编辑 收藏 引用 所属分类: Linux

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理