linux C 语言判断自身程序是否在运行

复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
//TF处理
#include <sys/vfs.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <errno.h> //时间 #include <time.h> #include <sys/time.h> #include <iostream> #include <cstring> #include <iostream> #include <sstream>

 

 

int isRunning(const char *procname)
{
    int ret = 0;
    char sCurrPid[16] = {0};
    sprintf(sCurrPid, "%d\n", getpid());
    
    FILE *fstream=NULL;    
    char buff[1024] = {0};  
 
    snprintf(buff,1024,"ps | grep %s | grep -v grep | awk '{print $1}'",procname);
    if(NULL==(fstream=popen(buff, "r")))    
    {   
        fprintf(stderr,"execute command failed: %s", strerror(errno));    
        return -1;    
    }  
    memset(buff, 0, sizeof(buff));
    while(NULL!=fgets(buff, sizeof(buff), fstream)) {
        if (strlen(buff) > 0) {
            if (strcmp(buff, sCurrPid) !=0) {
                //printf("******%s, %s****\n", buff, sCurrPid); 
                ret = 1;
                break;
            }
        }
    }
    pclose(fstream);
    return ret;
}

int main(int argc, char const *argv[])
{
    if(1==isRunning(argv[0])) {
        printf("is running\n");
        return 0;
    }
    while(1) {
        sleep(1);
    }
    return 0;
}
复制代码

 

posted @   cogitoergosum  阅读(450)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示