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]$ 
相关推荐
fengyehongWorld1 小时前
TeraTerm ttl脚本登录wsl
linux·teraterm
乌托邦的逃亡者2 小时前
Linux中如何检测IP冲突
linux·运维·tcp/ip
一曦的后花园2 小时前
linux搭建promethes并对接node-exporter指标
linux·运维·服务器
乌托邦的逃亡者3 小时前
CentOS/Openeuler主机中,为一个网卡设置多个IP地址
linux·运维·网络·tcp/ip·centos
桌面运维家3 小时前
服务器进程异常监控:快速定位与排障实战指南
运维·服务器
@CLoudbays_Martin114 小时前
UniApp是否能够接入SDK游戏盾呢?
服务器·网络·网络协议·tcp/ip·安全
念恒123064 小时前
进程控制---自定义Shell
linux·c语言
风曦Kisaki4 小时前
# Linux Shell 编程入门 Day02:条件测试、if 判断、循环与随机数
linux·运维·chrome
郝亚军4 小时前
ubuntu 22.04如何安装libmodbus
运维·服务器·ubuntu
李日灐4 小时前
< 6 > Linux 自动化构建工具:makefile 详解 + 进度条实战小项目
linux·运维·服务器·后端·自动化·进度条·makefile