Chinaunix首页 | 论坛 | 博客
  • 博客访问: 13679
  • 博文数量: 1
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2014-04-21 11:02
文章分类

全部博文(1)

文章存档

2014年(1)

我的朋友
最近访客

分类: LINUX

2014-04-23 21:14:23

proc文件系统中,相应进程目录下有个关于进程状态的文件stat(status也以较好的易读性记录着进程的状态)
解析/proc/%d/stat文件,可得到相应进程的状态

解析过程如下:

点击(此处)折叠或打开

  1. int monitor(){
  2.     char* tmp_fn = ( char* )malloc( 1024 ); //存储proc文件系统中对应进程所在的目录
  3.     snprintf( tmp_fn , 1024 , "/proc/%d/stat" , pid);//此处pid为所要监控的进程号

  4.     FILE* f = fopen( tmp_fn , "r" );
  5.     char* stat_line = ( char* )malloc( 1024 );//存储/proc/%d/stat文件中的前一部分字符串用以提取进程状态
  6.     memset(stat_line, 0, sizeof(stat_line) );//理解为对stat_line的初始化
  7.     fgets( stat_line , 1024 , f );//读取stat文件前一部分字符以方便提取进程状态标志
  8.     fclose( f );

  9.     char * stat_ptr = strrchr( stat_line , ')' );//截取从')'末次出现位置开始的子字符串
  10.     if( stat_ptr != NULL ){
  11.         char tmp;
  12.         stat_ptr += 2;
  13.         sscanf( stat_ptr, "%c", &tmp );//sscanf函数以传入的字符串为输入源
  14.         printf( "%c", tmp);
  15.     }
  16.     return 1;
  17. }

所涉及到的函数功能注释:
1. int snprintf(char* str, size_t size, const char* format,[arguments]...);
所需的头文件:#include
函数功能:将可变个参数(...)按照format给定的格式,格式化为字符串,然后将其复制到str中
如果格式化的字符串长度后的长度>size,则只将其中的(size-1)个字符复制到\str中,并给其后添加’\0’
返回值:实际格式化后的字符串的长度;出错则返回负值


个人理解:重定向了输出
此函数与sprintf的区别日后添上

点击(此处)折叠或打开

  1. char* tmp = (char*) malloc (1024);
  2. snprintf( tmp, 1024, "%s%d", "abc", 24);
  3. puts(tmp);//abc24

2. int sscanf(const char* buffer, const char* format,[arguments]…)
头文件:#include
函数功能:从buffer读进数据,依照format 的格式将数据写进arguments中(可通过format灵活的控制所想要读入的数据)
返回值:成功返回参数数目,失败返回-1

个人理解:输入源的重定向

点击(此处)折叠或打开

  1. char* s = "hello,23";
  2. char* tmp = (char*) malloc(6);
  3. int i = 0;
  4. sscanf( s, "%[^,],%d", tmp ,&i );// %[^,]表示一直匹配非,的字符
  5. puts(tmp);//打印出hello
  6. printf("%d", i);//打印出23

3.void *memset(void *s, int ch, size_t n);
头文件:#include
函数功能:将s中的前n个字节,用ch替换并返回s(可对较大的结构体或数组进行清零操作的一种最快方法)


4.char* strrchr(const char* str, char c )
头文件:#include
函数功能:查找字符c在字符串str中末次出现的位置,并返回从这个位置起直到字符串结束的子字符串;如未能找到返回NULL














阅读(2058) | 评论(0) | 转发(0) |
0

上一篇:没有了

下一篇:没有了

给主人留下些什么吧!~~