Linux中C后台服务程序单进程控制的示例分析
发表于:2024-09-21 作者:千家信息网编辑
千家信息网最后更新 2024年09月21日,这篇文章将为大家详细讲解有关Linux中C后台服务程序单进程控制的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。介绍通常后台服务器程序都必须有且只有一个进程
千家信息网最后更新 2024年09月21日Linux中C后台服务程序单进程控制的示例分析
这篇文章将为大家详细讲解有关Linux中C后台服务程序单进程控制的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
介绍
通常后台服务器程序都必须有且只有一个进程,那么如何单进程呢?
本例子是通过flock函数对/var/run/myserver.pid记录pid文件的进行加锁
若加锁不正常,说明后台服务进程已经在运行了,这时则直接报错退出
若加锁成功,说明后台服务进程没有在运行,这时可以正常启用进程
后台服务程序单进程控制
代码
#include#include #include #include #include #include #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=6965myserver 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 myserverroot 6965 0.0 0.0 3924 460 pts/0 S+ 00:32 0:00 | \_ ./myserverroot 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=11myserver process is running!!!!! Current process will exit !
关于"Linux中C后台服务程序单进程控制的示例分析"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
进程
运行
服务
程序
后台
文件
控制
篇文章
示例
分析
成功
只有
实例
更多
正在
检测
不错
实用
代码
例子
数据库的安全要保护哪些东西
数据库安全各自的含义是什么
生产安全数据库录入
数据库的安全性及管理
数据库安全策略包含哪些
海淀数据库安全审计系统
建立农村房屋安全信息数据库
易用的数据库客户端支持安全管理
连接数据库失败ssl安全错误
数据库的锁怎样保障安全
严重的网络安全
浙江专业服务器价格
杭州索尔网络技术
自动化专业需要的软件开发
python轻量级数据库实操
互联网科技和文创
固态硬盘服务器闪存
中国软件开发名企
无线网络技术填空题答案
数据库部署到远程服务器原理
win10DNS服务器可能不可用
网络技术专科好找工作吗
浪潮服务器安装win7虚拟机
实用数据库技术学习课本
数据库索引的查询机制
服务器系统探测
移动支付 网络安全问题
数据库技术应用物流时间
关于网络安全的基本知识
芒市网络安全
服务器盾牌
大华股份软件开发
滨州服务器运维管理系统销售
搭建方舟服务器
江苏仟渔网络技术有限公司电话
unity数据库开发书籍
服务器阵列管理怎么进
如何连接港澳台服务器
软件开发的技术交底
软件开发去外包公司