怎么用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);
}
}