怎么用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(filenam