Chinaunix首页 | 论坛 | 博客
  • 博客访问: 194369
  • 博文数量: 39
  • 博客积分: 1491
  • 博客等级: 上尉
  • 技术积分: 411
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-05 16:12
文章分类

全部博文(39)

文章存档

2011年(3)

2010年(6)

2009年(30)

我的朋友

分类: C/C++

2009-02-12 14:53:46


char PIDFILE[256] = "/tmp/proc_sle_sav.pid";
   
  static int lock_reg(int fd, int cmd, int type, off_t offset, int whence, off_t len)
  {
          struct flock lock;
   
          lock.l_type = type;
          lock.l_start = offset;
          lock.l_whence = whence;
          lock.l_len = len;
   
          return (fcntl(fd,cmd, &lock));
  }
   
  #define write_lock(fd, offset, whence, len) lock_reg(fd, F_SETLK, F_WRLCK, offset, whence, len)
   
  int check_single_on()
  {
          int fd, val;
          char buf[10];
   
          if((fd = open(PIDFILE, O_WRONLY | O_CREAT, 0644)) <0 ) {
                  perror("open in check_single_on()");
                  exit(1);
          }
   
          /* try and set a write lock on the entire file */
          if(write_lock(fd, 0, SEEK_SET, 0) <0 ) {
                  if(errno == EACCES || errno == EAGAIN) {
                          //printf("daemon is already running.\n");
                          //exit(0); /* gracefully exit, daemon is already running */
                          return 1;
                  }else {
                          perror("write_lock");
                          close(fd);
                          exit(1);
                  }
          }
   
          /* truncate to zero length, now that we have the lock */
          if(ftruncate(fd, 0) <0) {
                  perror("ftruncate");
                  close(fd);
                  exit(1);
          }
   
          /* write our process id */
          sprintf(buf, "%d\n", getpid());
          if(write(fd, buf, strlen(buf)) != strlen(buf)) {
                  perror("write in check_single_on()");
                  close(fd);
                  exit(1);
          }
   
          /* set close-on-exec flag for descriptor */
          if((val = fcntl(fd, F_GETFD, 0) <0 )) {
                  perror("fcntl");
                  close(fd);
                  exit(1);
          }
          val |= FD_CLOEXEC;
          if(fcntl(fd, F_SETFD, val) <0 ) {
                  perror("fcntl again");
                  close(fd);
                  exit(1);
          }
   
          /* leave file open until we terminate: lock will be held */
          return 0;
  }
   
   
  int main()
  {
  if(check_single_on())
  {
  printf("Aready runing.\n");
  return 0;
  }
   
  printf("BEGIN.\n");
  sleep(100);
  printf("END.\n");
  return 0;
  }

阅读(1279) | 评论(0) | 转发(0) |
0

上一篇:mount

下一篇:strip

给主人留下些什么吧!~~