Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97112
  • 博文数量: 6
  • 博客积分: 157
  • 博客等级: 民兵
  • 技术积分: 102
  • 用 户 组: 普通用户
  • 注册时间: 2012-12-25 14:18
文章分类

全部博文(6)

文章存档

2013年(1)

2012年(5)

分类: LINUX

2012-12-25 15:10:29

作为一个共享库,应该需要统计使用本库的各种应用程序的使用频率,使用方法等信息。才能针对主要应用做出更好的改进。
那么就需要记录调用者的进程id或者进程名称,并且保存下来。
保存的动作可以采用共享内存,也可以采用文件,这个在下篇博文描述,本文描述如何获取进程id和进程名称。
范例:

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>

  3. #define CFGMNG_TASK_NAME_LEN 256

  4. int main()
  5. {
  6.     int ret;
  7.     char ac_tmp[CFGMNG_TASK_NAME_LEN];
  8.   ret = cfgmng_get_taskname(ac_tmp, CFGMNG_TASK_NAME_LEN);
  9.   if (0 != ret) {
  10.       printf("Call cfgmng_get_taskname fail.\n");
  11.       return -1;
  12.   }
  13.   printf("The running task name is %s.\n", ac_tmp);
  14.   return 0;
  15. }


  16. int cfgmng_get_taskname(char *ac, int len)
  17. {
  18.     int count = 0;
  19.     int nIndex = 0;
  20.     char chPath[CFGMNG_TASK_NAME_LEN] = {0};
  21.     char cParam[100] = {0};
  22.     char *cTem = chPath;
  23.     int tmp_len;

  24.     pid_t pId = getpid();
  25.     sprintf(cParam,"/proc/%d/exe",pId);
  26. /*    printf("cParam = %s.\n", cParam);*/
  27.     count = readlink(cParam, chPath, CFGMNG_TASK_NAME_LEN);
  28. /*    printf("count = %d.\n", count);*/
  29.     if (count < 0 || count >= CFGMNG_TASK_NAME_LEN)
  30.     {
  31.         printf("Current System Not Surport Proc.\n");
  32.         return -1;
  33.     }
  34.     else
  35.     {
  36.         nIndex = count - 1;

  37.         for( ; nIndex >= 0; nIndex--)
  38.         {
  39.             if( chPath[nIndex] == '/' )//筛选出进程名
  40.             {
  41.                 nIndex++;
  42.                 cTem += nIndex;
  43.                 break;
  44.             }
  45.         }
  46.     }
  47.     tmp_len = strlen(cTem);
  48.     if (0 == tmp_len) {
  49.         printf("Get task fail.\n");
  50.         return -1;
  51.     }
  52.     
  53.     if (len <= tmp_len +1) {
  54.         printf("len(%d) is less than taskname(%s)'s len.\n", len, cTem);
  55.         return -1;
  56.     }
  57.     
  58.     strcpy(ac, cTem);
  59.     
  60.     return 0;
  61. }
从上面的实验范例可以看出,主要使用的函数是getpid获取本进程的id,再到/proc/pid/exe中去找到对应的进程名称。在/proc目录中有很多跟进程相关的东西,都可以用这种方法触类旁通地实现。
阅读(17487) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~