现在的位置: 首页 > 综合 > 正文

对进程个数计数

2013年12月05日 ⁄ 综合 ⁄ 共 980字 ⁄ 字号 评论关闭

 在linux怎么知道一个指定的“进程名”有几个在运行了呢?

下面这下例子演示了这个过程,计数函数为:getProcessCount()

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


// 获取进程数量
int getProcessCount(char *processname)
{
	FILE *ptr;
	char buff[512], ps[128];
	int count = -1;

	sprintf(ps, "ps -e|grep -c ' %s$'", processname);	// 对指定的进程名计数(求个数)
	if((ptr = popen(ps, "r")) != NULL)
	{
		if(fgets(buff, 512, ptr) != NULL)
		{
			count = atoi(buff);
		}
	}
	pclose(ptr);

	return count;
}

int main(int argc, char *argv[])
{
	if(argc == 2)
	{
		int ret = getProcessCount(argv[1]);			// 获取进程数量
		printf("Count[%s] = %d\n", argv[1], ret);
	}
	else
	{
		printf("Usage error!\n");
	}
	return 0;
}

如果要判断某个进程是否存在的话,只要判断这个进程的个数就知道了。小于1就是不存在,否则存在。

 

 参考了网上的代码:http://blog.csdn.net/lanmanck/article/details/6021878

int detect_process(char * process_name)  
{  
        FILE *ptr;  
        char buff[512];  
        char ps[128];  
        sprintf(ps,"ps -e | grep -c ' %s</p>",process_name);  
        strcpy(buff,"ABNORMAL");  
        if((ptr=popen(ps, "r")) != NULL)  
        {  
                while (fgets(buff, 512, ptr) != NULL)  
                {  
                        if(atoi(buff)>=2)  
                        {  
                                pclose(ptr);  
                                return CONFLICT;  
                        }  
                }  
        }  
        if(strcmp(buff,"ABNORMAL")==0)  /*ps command error*/  
         return ERROR;          
        pclose(ptr);  
        return NOERROR;  
}

抱歉!评论已关闭.