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]$ 
相关推荐
yzx99101318 分钟前
服务器生成图片
运维·服务器
db_murphy1 小时前
Oracle数据块8KB、OS默认认块管理4KB,是否需调整大小为一致?
linux
liulilittle2 小时前
C++ TAP(基于任务的异步编程模式)
服务器·开发语言·网络·c++·分布式·任务·tap
mCell4 小时前
从删库到跑路?这50个Linux命令能保你职业生涯
linux·windows·macos
杰克逊的日记4 小时前
GPU运维常见问题处理
linux·运维·gpu
caolib5 小时前
无需云服务器的内网穿透方案 -- cloudflare tunnel
运维·服务器·内网穿透·tunnel·cloudflared
誰能久伴不乏5 小时前
Linux系统调用概述与实现:深入浅出的解析
linux·运维·服务器
程序员学习随笔6 小时前
Linux进程深度解析(2):fork/exec写时拷贝性能优化与exit资源回收机制(进程创建和销毁)
linux·运维·服务器
mmoyula6 小时前
【RK3568 PWM 子系统(SG90)驱动开发详解】
android·linux·驱动开发
-SGlow-6 小时前
MySQL相关概念和易错知识点(2)(表结构的操作、数据类型、约束)
linux·运维·服务器·数据库·mysql