1. gzyueqian
      13352868059
      首頁 > 新聞中心 > > 正文

      在Linux下防止某個程序被運行兩次的方法

      更新時間: 2008-04-22 15:10:43來源: 粵嵌教育瀏覽量:438

        通過文件鎖來實現,在程序運行的一開始,檢查某文件是否存在,如果存在則說明改程序已經在運行了,如果不存在則利用open語句創建該文件,程序退出時關閉并刪除此文件。

      static char file_lock[sizeof(ctl_addr.sun_path)] = /var/run/file.pid;
                    static bool file_lock_created = FALSE;
                    
                    static int
                    create_lock(void)
                    {
                     int fd = open(file_lock, O_WRONLY | O_CREAT | O_EXCL | O_TRUNC,
                     S_IRUSR | S_IRGRP | S_IROTH);
                    
                     if (fd < 0)
                     {
                     if (errno == EEXIST)
                     {
                     fprintf(stderr, "file: lock file \"%s\" already exists\n", file_lock);
                     exit_file(10);
                     }
                     else
                     {
                     fprintf(stderr, "file: unable to create lock file \"%s\" (%d %s)\n"
                     , file_lock, errno, strerror(errno));
                     exit_file(1);
                     }
                     }
                     file_lock_created = TRUE;
                     return fd;
                    }
                    
                    static bool
                    fill_lock(int lockfd)
                    {
                     char buf[30]; /* holds "\n" */
                     pid_t pid;
                     int len;
                    
                     pid = getpid();
                     len = snprintf(buf, sizeof(buf), "%u\n", (unsigned int) pid);
                     bool ok = len > 0 && write(lockfd, buf, len) == len;
                    
                     close(lockfd);
                     return ok;
                    }
                    
                    static void
                    delete_lock(void)
                    {
                     if (file_lock_created)
                     {
                     //delete_ctl_socket();
                     unlink(file_lock); /* is noting failure useful? */
                     }
                    }

      免費預約試聽課

      亚洲另类欧美综合久久图片区_亚洲中文字幕日产无码2020_欧美日本一区二区三区桃色视频_亚洲AⅤ天堂一区二区三区

      
      

      1. 五月婷婷精品视频在线播放 | 亚洲成AV人片女在线观看 | 色五月日韩中文在线 | 亚洲手机在线人成9视频 | 亚洲国产欧美在线成人Aⅴ 午夜在线a亚洲v天堂网2019 | 久久精品伊人久久精品伊人 |