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]$ 
相关推荐
老友@9 分钟前
服务器异常宕机或重启导致 RabbitMQ 启动失败问题分析与解决方案
服务器·rabbitmq·启动失败·宕机
BD_Marathon13 分钟前
ubuntu防火墙使用
linux·ubuntu
dessler17 分钟前
Kafka-消费者(Consumer)和消费者组(Consumer Group)
linux·运维·kafka
kfepiza18 分钟前
Debian-10-standard用`networking`服务的`/etc/network/interfaces`配置文件设置多网卡多IPv6
linux·debian
程序猿追28 分钟前
免费版安全性缩水?ToDesk、TeamViewer、向日葵、网易UU远程访问&隐私防护测评
服务器·网络·科技·teamviewer
进击的程序汪28 分钟前
Linux 启动过程流程图--ARM版
linux·运维·arm开发
泡泡以安1 小时前
JA3指纹在Web服务器或WAF中集成方案
服务器·安全·https·ja3指纹
deeper_wind1 小时前
MySQL数据库基础(小白的“升级打怪”成长之路)
linux·数据库·mysql
Raners_1 小时前
【Linux】文件权限以及特殊权限(SUID、SGID)
linux·安全
egoist20231 小时前
【Linux仓库】进程优先级及进程调度【进程·肆】
linux·运维·服务器·进程切换·进程调度·进程优先级·大o1调度