当前位置: 首页 > news >正文

Linux进程单例模式运行

Linux进程单例模式运行

#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>int write_pid(const char* pidFile)
{char str[32] = {0};int fd = open(pidFile,O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);if(fd < 0){   printf("can't open pidFile %s.\n",pidFile);exit(1);}   //Lock pidFile.if(lockf(fd, F_TLOCK,0))printf("can't lock pidFile %s.\n",pidFile);exit(0);}   sprintf(str,"%d\n",getpid());//Write pid ot pidFilessize_t len = strlen(str);if(write(fd,str,len) != len){   printf("can't write pid %s.\n",pidFile);exit(0);}   printf("write pid file %s.\n",pidFile);return fd; 
}int main()
{int pid_fd = write_pid("server.pid");while(1){   ;}lockf(pid_fd, F_ULOCK,0);close(pid_fd);
}

终端1

[banting@localhost test]$ ls -tlr
-rw-rw-r--. 1 banting banting      834 Jun 30 15:53 test75.cpp
-rwxrwxr-x. 1 banting banting    19760 Jun 30 16:03 test75
[banting@localhost test]$ g++ -g test75.cpp -o test75
[banting@localhost test]$
[banting@localhost test]$ ./test75
write pid file server.pid.

终端2

[banting@localhost test]$ ps -ef |grep test75
banting   519636  596192 99 16:03 pts/38   00:00:38 ./test75
banting   519676  518705  0 16:04 pts/96   00:00:00 grep --color=auto test75
[banting@localhost test]$ cat server.pid 
519636
[banting@localhost test]$ ./test75
can't lock pidFile server.pid.
[banting@localhost test]$ 
http://www.lryc.cn/news/578107.html

相关文章:

  • 【AI News | 20250630】每日AI进展
  • 华为云Flexus+DeepSeek征文 | 从零开始搭建Dify-LLM应用开发平台:华为云全流程单机部署实战教程
  • 本地部署kafka4.0
  • Serverless 架构入门与实战:AWS Lambda、Azure Functions、Cloudflare Workers 对比
  • 打卡day58
  • 逻辑门电路Multisim电路仿真汇总——硬件工程师笔记
  • 设计模式(六)
  • 深入拆解AOP的Java技术栈:注解、反射与设计模式的完美融合
  • [springboot系列] 探秘JUnit 5: Java单元测试利器
  • xilinx axi datamover IP使用demo
  • 网络协议之网络探测协议ICMP及其应用ping,traceroute
  • Prompt 精通之路(七)- 你的终极 AI 宝典:Prompt 精通之路系列汇总
  • python+uniapp基于微信小程序蜀味道江湖餐饮管理系统nodejs+java
  • Java开发新变革!飞算JavaAI深度剖析与实战指南
  • 计算机是如何⼯作的
  • 【Java EE初阶】计算机是如何⼯作的
  • Android 中 使用 ProgressBar 实现进度显示
  • vue中表尾合计
  • 车载Tier1 supplier梳理
  • Android阴影效果的艺术与实现:从入门到精通
  • Linux 安装使用教程
  • C++ 第四阶段 STL 容器 - 第五讲:详解 std::set 与 std::unordered_set
  • 【甲方安全建设】SDL基线建设及审计评估
  • Linux习题
  • 机器学习,支持向量机svm和决策树xgboost介绍
  • 【读代码】TradingAgents:基于多智能体LLM的金融交易框架深度解析
  • 大模型的开发应用(十六):Agent 与 LangGraph基础
  • Waiting for another flutter command to release the startup lock...解决方法
  • 9.6 视觉专家模块+1536超清解析!智谱CogVLM-9B多模态模型中文场景实战评测,性能炸裂吊打LLaVA
  • Python 机器学习实战:泰坦尼克号生还者预测 (从数据探索到模型构建)