欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Linux C 后臺服務(wù)程序單進程控制的實現(xiàn)

 更新時間:2019年09月01日 09:28:05   作者:小林coding  
這篇文章主要介紹了Linux C 后臺服務(wù)程序單進程控制的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

介紹

通常后臺服務(wù)器程序都必須有且只有一個進程,那么如何單進程呢?

本例子是通過flock函數(shù)對/var/run/myserver.pid記錄pid文件的進行加鎖

  • 若加鎖不正常,說明后臺服務(wù)進程已經(jīng)在運行了,這時則直接報錯退出
  • 若加鎖成功,說明后臺服務(wù)進程沒有在運行,這時可以正常啟用進程

后臺服務(wù)程序單進程控制

詳細不多說,直接看代碼

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>

#define PID_BUF_LEN  (20)
#define RUN_PID_FILE "/var/run/myserver.pid"

//服務(wù)進程單實例運行
//返回值: 1--正在運行,0--未運行,-1--出錯
int server_is_running()
{
  int fd = open(RUN_PID_FILE, O_WRONLY|O_CREAT);
  if(fd < 0)
  {
    printf("open run pid err(%d)! %s\n", errno, RUN_PID_FILE);
    return -1;
  }
   
  // 加鎖
  // LOCK_SH 建立共享鎖定。多個進程可同時對同一個文件作共享鎖定。
  // LOCK_EX 建立互斥鎖定。一個文件同時只有一個互斥鎖定。
  if(flock(fd, LOCK_EX|LOCK_NB) == -1)
  {
    //加不上鎖,則是服務(wù)正在運行,已上鎖了
    printf("server is runing now! errno=%d\n", errno);
    close(fd);
    return 1;
  }

  // 加鎖成功,證明服務(wù)沒有運行
  // 文件句柄不要關(guān),也不要解鎖
  // 進程退出,自動就解鎖了
  printf("myserver is not running! begin to run..... pid=%ld\n", (long)getpid());

  char pid_buf[PID_BUF_LEN] = {0};
  snprintf(pid_buf, sizeof(pid_buf)-1, "%ld\n", (long)getpid());

  // 把進程pid寫入到/var/run/myserver.pid文件
  write(fd, pid_buf, strlen(pid_buf));

  return 0;
}

int main(void)
{

  //進程單實例運行檢測
  if(0 != server_is_running())
  {
    printf("myserver process is running!!!!! Current process will exit !\n");
    return -1;
  }

  while(1)
  {
    printf("myserver doing ... \n");
    sleep(2);
  }

  return 0;
}

運行結(jié)果

運行程序,可知進程pid是6965

[root@lincoding singleprocess]# ./myserver 
server is not running! begin to run..... pid=6965
myserver doing ... 
myserver doing ... 
myserver doing ... 
myserver doing ... 
myserver doing ... 
myserver doing ... 
myserver doing ... 
myserver doing ... 

/var/run/myserver.pid 也記錄此進程的pid號,ps auxf | grep myserver可知mysever進程一直運行著

[root@lincoding singleprocess]# cat /var/run/myserver.pid 
6965
[root@lincoding singleprocess]# 
[root@lincoding singleprocess]# ps auxf | grep myserver
root   6965 0.0 0.0  3924  460 pts/0  S+  00:32  0:00 |    \_ ./myserver
root   9976 0.0 0.0 103256  856 pts/1  S+  00:35  0:00     \_ grep myserver
[root@lincoding singleprocess]# 

此時,再運行myserver程序,這時會報錯退出,因為檢測到myserver程序已經(jīng)在運行中,不可以起另外一個進程,從而達到了后臺服務(wù)程序單進程控制

[root@lincoding singleprocess]# ./myserver 
server is runing now! errno=11
myserver process is running!!!!! Current process will exit !

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論