zoukankan      html  css  js  c++  java
  • linux 检测进程是否存在

    1. 直接遍历/proc目录

      

    int find_pid_by_name( char* pidname, pid_t *pidlist)
    {
    #define READ_BUF_SIZE 256
    
        DIR *dir;
        struct dirent *next;
        int i = 0;
     
        dir = opendir("/proc");
    
    		if (!dir)
        {
        	printf("Cannot open /proc");
    		}
         
        while ((next = readdir(dir)) != NULL) 
    		{
            FILE *status;
            char filename[READ_BUF_SIZE];
            char buffer[READ_BUF_SIZE];
            char name[READ_BUF_SIZE];
     
            /* Must skip ".." since that is outside /proc */
            if (strcmp(next->d_name, "..") == 0)
                continue;
     
            /* If it isn't a number, we don't want it */
            if (!isdigit(*next->d_name))
                continue;
    
            sprintf(filename, "/proc/%s/status", next->d_name);
            if (! (status = fopen(filename, "r")) ) 
    				{
                continue;
            }
    				
            if (fgets(buffer, READ_BUF_SIZE-1, status) == NULL) 
    				{
                fclose(status);
                continue;
            }
    				
            fclose(status);
     
            /* Buffer should contain a string like "Name:   binary_name" */
            sscanf(buffer, "%*s %s", name);
            if (strcmp(name, pidname) == 0) 
    				{
    						pidlist[i++] = strtol(next->d_name, NULL, 0);
            }
        }
    
    	return i;
    }
    
    int is_cap_running()
    {
    	pid_t pid_list[128];
    
    	if(find_pid_by_name("capSrv", pid_list) > 1)
    	{
    		printf("capSrv already run, pid:%u 
    ", 
    				(pid_list[0] == getpid()) ? pid_list[1] : pid_list[0]);
    		return 1;
    	}
    	else
    	{
    		return 0;
    	}
    }
    

      

     2. 调用pidof

    char buf[256] = {0};
    	int pos = 0;
    	pid_t cur_pid = getpid();
    	
    	char *cmd = "pidof capSrv";
    	FILE *file = popen(cmd, "r");
    
    
    	while(fgets(buf, 256, file) != NULL)
    	{
    		printf("%s fgets: %s 
    ", cmd, buf);		
    		if(isdigit(buf[0]))
    		{
    			pclose(file);
    			
    			if(sscanf(buf,"%u %u", &pid[0],pid[1]) == 2)
    			{
    				printf("capSrv already run, pid:%u 
    ", (pid[0] == cur_pid) ? pid[1] : pid[0]);
    				return 1;
    			}
    			else
    			{
    				return 0;
    			}
    		}
    	}
    

     3. ps 

  • 相关阅读:
    js获得动态生成的标签
    自定义字段在List和ClassList等标签里的使用方法
    asp.net dropdownlist 取不到值
    MXCMS新增标签IFrame 包含标签
    JS打印
    Flash图表解决方案 Finger Chart
    推荐个免费的客户端控件
    C#利用反射获取对象属性值
    位置导航MXCMS Position标签说明
    OAuth简介
  • 原文地址:https://www.cnblogs.com/iclk/p/3829106.html
Copyright © 2011-2022 走看看