LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 795|回复: 4

如何防止一个程序启动两次?

[复制链接]
发表于 2004-6-1 22:47:05 | 显示全部楼层 |阅读模式
rt 。win下有mutex,不知linux下有什么方法?
发表于 2004-6-1 23:06:24 | 显示全部楼层
lock file
 楼主| 发表于 2004-6-1 23:46:05 | 显示全部楼层
如果加锁的程序死了,或者coredump出来,是否会释放lock?
发表于 2004-6-2 00:24:32 | 显示全部楼层

  1. const char filename[]  = "/tmp/lockfile"
  2. int fd = open (filename, O_WRONLY | O_CREAT | O_EXCL, 0644);
  3. if (fd == -1) {
  4.         perror("open lockfile");
  5.         return -1;
  6. }
  7. /*
  8. * this will decrease the link count of the lock file to zero,
  9. * and the OS will remove the file when this process exit (abnormally)
  10. */
  11. unlink(filename);
复制代码
 楼主| 发表于 2004-6-2 23:04:42 | 显示全部楼层
感谢chaisave的启发。我的测试例子如下:


  1. cat lock.c
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <sys/file.h>

  5. main()
  6. {
  7.     const char filename[]  = "/home/mylockfile";
  8.     char a[1];
  9.     int fd = open (filename,O_CREAT|O_WRONLY , 0644);
  10.     int lock =  lockf(fd,F_TLOCK,0);
  11.     if (fd == -1)
  12.     {
  13.         perror("open file");
  14.        return -1;
  15.     }
  16.     if (lock == -1)
  17.     {
  18.         perror("lock fail");
  19.         return -1;
  20.     }
  21.      //use unlink then not have any file ,then second process can do same thing again
  22.     //unlink(filename);
  23.     while(1)
  24.     {
  25.         sleep(10);
  26.         //test core dump
  27.         printf("%s",a[2]);
  28.     }
  29. }

复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表