温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Linux中C后台服务程序单进程控制的示例分析

发布时间:2021-07-16 14:47:48 来源:亿速云 阅读:110 作者:小新 栏目:服务器

这篇文章将为大家详细讲解有关Linux中C后台服务程序单进程控制的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

介绍

通常后台服务器程序都必须有且只有一个进程,那么如何单进程呢?

本例子是通过flock函数对/var/run/myserver.pid记录pid文件的进行加锁

  • 若加锁不正常,说明后台服务进程已经在运行了,这时则直接报错退出

  • 若加锁成功,说明后台服务进程没有在运行,这时可以正常启用进程

后台服务程序单进程控制

代码

#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"

//服务进程单实例运行
//返回值: 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)
  {
    //加不上锁,则是服务正在运行,已上锁了
    printf("server is runing now! errno=%d\n", errno);
    close(fd);
    return 1;
  }

  // 加锁成功,证明服务没有运行
  // 文件句柄不要关,也不要解锁
  // 进程退出,自动就解锁了
  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;
}

运行结果

运行程序,可知进程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程序已经在运行中,不可以起另外一个进程,从而达到了后台服务程序单进程控制

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

关于“Linux中C后台服务程序单进程控制的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI