Chinaunix首页 | 论坛 | 博客
  • 博客访问: 390847
  • 博文数量: 87
  • 博客积分: 2571
  • 博客等级: 少校
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-29 13:10
文章分类

全部博文(87)

文章存档

2012年(49)

2011年(7)

2010年(26)

2009年(5)

分类: LINUX

2012-03-28 18:23:20

需要/proc文件系统支持

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <dirent.h>
  4. #include <sys.types.h>

  5. #define MAXSIZE 124

  6. pid_t getPidByName( char* name )
  7. {
  8.  DIR *dirHandle;
  9.  struct dirent *dirEntry; // 单个目录项
  10.  pid_t pid = -1;
  11.  char strPathName[100];
  12.  FILE *fp;
  13.  char buff[MAXSIZE];

  14.  memset(strPathName,'0',100);
  15.  
  16.  if( (dirHandle = opendir("/proc")) == NULL )
  17.  {
  18.   return -1;
  19.  }

  20.  chdir("/proc");
  21.  while( (dirEntry = readdir(dirHandle)) != NULL)
  22.  {
  23.   if(dirEntry->d_name[0] != '.' && strcmp(dirEntry->d_name, "sys") !=0 )
  24.   {
  25.    sprintf(strPathName, "./%s/%s", dirEntry->d_name,"cmdline");
  26.    if( (fp = fopen(strPathName,"r") ) == NULL)
  27.    {
  28.     printf("failed to open %s/n",strPathName);
  29.     break;
  30.    }
  31.    
  32.    memset(buff,'0',MAXSIZE);
  33.    if( (int)fread(buff,MAXSIZE,1,fp) == -1)
  34.    {
  35.     printf("failed to read %s/n",strPathName);
  36.     fclose(fp);
  37.     break;
  38.    }
  39.    
  40.    if( strcmp(buff,name) == 0)
  41.    {
  42.     pid = (pid_t)atoi(dirEntry->d_name);
  43.    }
  44.    fclose(fp);
  45.   }
  46.  }
  47.  closedir(dirHandle);
  48.  return pid;
  49. }

阅读(3383) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~