<meter id="pryje"><nav id="pryje"><delect id="pryje"></delect></nav></meter>
          <label id="pryje"></label>

          新聞中心

          EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 在Linux下防止某個程序被運行兩次的方法

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

          作者: 時間:2016-10-08 來源:網(wǎng)絡(luò) 收藏

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

          本文引用地址:http://www.ex-cimer.com/article/201610/305725.htm

          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 existsn, 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), %un, (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? */

          }

          }



          關(guān)鍵詞:

          評論


          相關(guān)推薦

          技術(shù)專區(qū)

          關(guān)閉
          看屁屁www成人影院,亚洲人妻成人图片,亚洲精品成人午夜在线,日韩在线 欧美成人 (function(){ var bp = document.createElement('script'); var curProtocol = window.location.protocol.split(':')[0]; if (curProtocol === 'https') { bp.src = 'https://zz.bdstatic.com/linksubmit/push.js'; } else { bp.src = 'http://push.zhanzhang.baidu.com/push.js'; } var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(bp, s); })();