Linux进程单例模式运行

Linux进程单例模式运行

cpp 复制代码
#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 pidfile
    ssize_t len = strlen(str);
    
    if(write(fd,str,len) != len)
    {   
        printf("can't write pid %s.\n",pidFile);
        exit(0);
    }   
	//flush disk cache
	fdatasync(fd);
	
    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

bash 复制代码
[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

bash 复制代码
[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]$ 
相关推荐
jun_bai42 分钟前
Ecplise中发布项目到配置的tomcat中
java·服务器
芦柑4641 小时前
画布和3D导演台工具:短剧分镜从素材整理到空间预演的完整链路
服务器·前端·数据库
闲云野鹤在人间1 小时前
KVM虚拟化实战|CentOS‑Stream8 两种安装方式+模板制作+基础使用
linux·运维·服务器·centos
小张同学a.1 小时前
Docker 容器实战 2—— docker 仓库
linux·运维·服务器·docker·容器
Android系统攻城狮1 小时前
Linux PipeWire深度解析之pw_core_get_registry调用流程与实战(九十一)
linux·运维·服务器·音频进阶·pipewire音频实战进阶
小义_1 小时前
JDK 深度解析
java·linux·开发语言·python·面试
邪修king1 小时前
Re:Linux 系统编程篇 (十二):进程篇(一)基础与 fork 系统调用全解
linux·运维·服务器
牢姐与蒯1 小时前
Linux进程(五).之环境变量
linux·运维·服务器·ubuntu
raindayinrain2 小时前
深入理解Linux内核--系统调用,性能优化
linux·性能优化·系统调用·返回值·入参·内核态用户态地址访问
码上有光2 小时前
Linux:进程控制和进程替换
java·linux·服务器·进程控制·进程替换