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]$ 
相关推荐
大聪明-PLUS1 小时前
GCC 对 C 语言的扩展
linux·嵌入式·arm·smarc
大霞上仙1 小时前
jmeter实现两个接口的同时并发
运维·服务器·jmeter
Hello.Reader2 小时前
从零到一上手 Protocol Buffers用 C# 打造可演进的通讯录
java·linux·c#
nmxiaocui2 小时前
openssl升级
linux·运维·服务器
初学者_xuan3 小时前
零基础快速了解掌握Linux防火墙-Iptables
linux·服务器·防火墙·linux新手小白
HetFrame3 小时前
John the Ripper jumbo + HashCat 破解压缩密码 ubuntu amd GPU
linux·ubuntu·amd·密码破解·john·压缩密码·hashcat
百锦再4 小时前
在 CentOS 系统上实现定时执行 Python 邮件发送任务
java·linux·开发语言·人工智能·python·centos·pygame
zhao3266857514 小时前
海外代理IP平台Top3评测:LoongProxy、神龙动态IP、IPIPGO哪家更适合你?
服务器·网络·tcp/ip
最小的帆也能远航4 小时前
2018年下半年 系统架构设计师 综合知识
linux·运维·服务器
疯子@1235 小时前
nacos1.3.2 ARM 版容器镜像制作
java·linux·docker·容器