用C语言 实现ps | grep xxx 命令

怎么用C语言实现ps | grep xxx 命令

总的思路就是读取 /proc/文件, 里面的stat、cmdline。其中利用cmdline可以实现,因为里面是完整的cmd命令,但是可以处理其中稍微有点麻烦,它是以‘\0’做分隔符的

#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <dirent.h>

int find_pid_by_name_cmdline( char *ProcName, int *foundnum)
{
	
	DIR             *dir = NULL;
	struct dirent   *d = NULL;
	char str[256] = {0};
	char filename[256] = {0};
	FILE *fp = NULL;
	char *p = NULL;
	char *pstr = NULL;
	char *s
	int pid = 0;
	
	
	if ( NULL == ProcName || NULL == foundnum )
		return -1;
	

	dir = opendir("/proc");
	if (!dir)
	{
		printf("cannot open /proc");
		return -1;
	}
	

	while ((d = readdir(dir)) != NULL) {
		
		
		if ((pid = atoi(d->d_name)) == 0)
			continue;
		
		snprintf(filename, sizeof(filename), "/proc/%s/cmdline", d->d_name);
		
		fp = fopen(filename, "r");
		if(fp)
		{
			fgets(str, sizeof(str), fp);
			pstr = str;
			while( (p=strchr(pstr,'\0')) && '\0'!=(*(p+1)) )
			{
				pstr = p+1;
				*p = ' ';
				
			}
			if( strstr(str, ProcName) )
			{
				*foundnum = pid;
				closedir(dir);
				return 0;
			}
			fclose(fp);
		}
	}
	closedir(dir);
	printf("----------%s not exist ---------------", ProcName);
	return -1;
}


int find_pid_by_name_stat( char *ProcName, int *foundnum)
{
	
	DIR *dir = NULL;
	FILE *fp = NULL;
	struct dirent *d = NULL;
	char str[256] = {0};
	char filename[256] = {0};
	int pid = 0;
	char pname[128] = {0};
	
	
	if ( NULL == ProcName || NULL == foundnum )
		return -1;
	
	
	/* Open the /proc directory. */
	dir = opendir("/proc");
	if (!dir)
	{
		printf("cannot open /proc");
		printf("---------- cannot open proc %s ---------------", pname);
		return -1;
	}
	
	/* Walk through the directory. */
	while ((d = readdir(dir)) != NULL) {
		
		/* See if this is a process */
		if ((pid = atoi(d->d_name)) == 0)
			continue;
		
		snprintf(filename, sizeof(filename), "/proc/%s/stat", d->d_name);
		
		fp = fopen(filename, "r");
		if(fp)
		{
			fgets(str, sizeof(str), fp);
			fclose(fp);
			sscanf(str,"%d (%s", &pid, pname);
			pname[strlen(pname)-1]='\0';
			if(!strcmp(pname, ProcName))
			{
				printf("----------%s exist---------------", ProcName);
				*foundnum = pid;
				closedir(dir);
				return 0;
			}
		}
	}
	closedir(dir);
	printf("----------%s not exist ---------------", ProcName);
	return -1;
}

void main(int argc, char *argv[])
{
	int foundnum = 0;
	if(!find_pid_by_name_stat( argv[1], &foundnum))
	{
		printf("success pid:%d\n", foundnum);
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值