Chinaunix首页 | 论坛 | 博客
  • 博客访问: 431114
  • 博文数量: 53
  • 博客积分: 2746
  • 博客等级: 少校
  • 技术积分: 829
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-14 10:41
文章分类

全部博文(53)

文章存档

2016年(2)

2013年(1)

2012年(7)

2011年(10)

2010年(5)

2009年(20)

2008年(8)

我的朋友

分类: LINUX

2012-10-18 10:57:41


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5. #include <fcntl.h>

  6. static char *saved_pidfile;

  7. static void pidfile_delete(void)
  8. {
  9.         if (saved_pidfile) unlink(saved_pidfile);
  10. }

  11. int pidfile_acquire(const char *pidfile)
  12. {
  13.         int pid_fd;
  14.         if (!pidfile) return -1;

  15.         pid_fd = open(pidfile, O_CREAT | O_WRONLY, 0644);
  16.         if (pid_fd < 0) {
  17.                 printf("Unable to open pidfile %s: %m\n", pidfile);
  18.         } else {
  19.                 lockf(pid_fd, F_LOCK, 0);
  20.                 if (!saved_pidfile)
  21.                         atexit(pidfile_delete);
  22.                 saved_pidfile = (char *) pidfile;
  23.         }
  24.         return pid_fd;
  25. }

  26. void pidfile_write_release(int pid_fd)
  27. {
  28.         FILE *out;

  29.         if (pid_fd < 0) return;

  30.         if ((out = fdopen(pid_fd, "w")) != NULL) {
  31.                 fprintf(out, "%d\n", getpid());
  32.                 fclose(out);
  33.         }
  34.         lockf(pid_fd, F_UNLCK, 0);
  35.         close(pid_fd);
  36. }

  37. void create_pidfile(void)
  38. {
  39.         int fd;
  40.         fd = pidfile_acquire("/var/run/gpio.pid");
  41.         pidfile_write_release(fd);
  42. }

  43. int main(int argc, char *argv[])
  44. {
  45.         create_pidfile();
  46.         return 0;
  47. }

阅读(6540) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~