Linux C++ 通过PID文件判断进程是否运行

1.环境:Linux localhost.localdomain 3.10.0-1127.el7.x86_64  x86_64 x86_64 x86_64 GNU/Linux

2.文件运行权限:root

3.代码

#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
#include<signal.h>
#include<iostream>
static char * starter_pid_file_default="/var/run/test.pid";
static bool check_pid(char* pid_file)
{
        struct stat stb;
        FILE * pidfile;
        if(stat(pid_file,&stb)==0)
        {
                pidfile=fopen(pid_file,"r");
                if(pidfile)
                {
                        char buf[64];
                        pid_t pid=0;
                        memset(buf,0,sizeof(buf));
                        if(fread(buf,1,sizeof(buf),pidfile))
                        {
                                buf[sizeof(buf)-1]='\0';
                                pid=atoi(buf);
                        }
                        fclose(pidfile);
                        if(pid && kill(pid,0)==0)
                        {
                                std::cout<<"such  a  process  is running \n";
                                return 1;
                        }
                }
        std::cout<<"removing pidfile ,process not running "<<pid_file<<std::endl;
        unlink(pid_file);

        }
return 0;
}
int  main()
{
        FILE *fd=fopen(starter_pid_file_default,"w");
        if(fd)
        {
                fprintf(fd,"%u\n",getpid());
                fclose(fd);
        }
        if(check_pid(starter_pid_file_default))
        {
                std::cout<<"test is  already running  exeits  "<<starter_pid_file_default<<"\n  test process Pid: "<<getpid()<<std::endl;
        }
        else
                std::cout<<"test is   not exeits  "<<starter_pid_file_default<<std::endl;
        unlink(starter_pid_file_default);
return 0;
}
代码解析:

代码中,check_pid是一个自定义函数,用来检查PID文件是否存在,继而判断进程是否运行。因为整个程序设计的思路是程序刚刚启动的时候,会创建一个/var/run/test.pid文件,并把本进程的进程号写入该文件中。在check_pid中,用了stat函数判断文件是否存在。为保险起见,又用fopen打开了一次。如果存在,就读该文件的进程号,然后通过kill函数检查该进程是是否在运行。kill函数的第二个参数表示准备发送信号代码,如果为0,则没有任何信号送出,但是系统会执行错误检查,通常利用sig值为0来检查某个进程是否在执行;

程序结束的时,也就是程序即将退出的时,会删除PID文件。

3、编译、运行‘

编译:g++ test.cpp  -o test

运行: ./test 如图:

猜你喜欢

转载自blog.csdn.net/xiaoshunzi111/article/details/112397059