Chinaunix首页 | 论坛 | 博客
  • 博客访问: 109663
  • 博文数量: 57
  • 博客积分: 1200
  • 博客等级: 中尉
  • 技术积分: 555
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-26 21:13
文章分类

全部博文(57)

文章存档

2012年(14)

2011年(43)

分类: LINUX

2011-12-21 11:10:42

1.backtrace与backtrace_symbols       打印栈信息,在调试器不能使用的情况下,有用。
  1. int backtrace(void **buffer, int size);
  2. char **backtrace_symbols(void *const *buffer, int size);

  3. void backtrace_symbols_fd(void *const *buffer, int size, int fd);
示例代码:
  1. void print_stack(void)
  2. {
  3.     static char stack_info[MAXLINE];
  4.     const int max_depth = 200;
  5.     void *func_array[max_depth];

  6.     int nptrs = backtrace(func_array, max_depth);
  7.     printf ( "there are %d pointers\n", nptrs);

  8.     char **strings = backtrace_symbols(func_array, nptrs);
  9.     char *stack_ptr = stack_info;
  10.     int nlen = 0;

  11.     if (strings)
  12.     {
  13.         int index = 0;
  14.         memset(stack_info, '\0', sizeof(stack_info));
  15.         for (; index < nptrs; ++index)
  16.         {
  17.             nlen = sprintf(stack_ptr, "%s\n", strings[index]);
  18.             stack_ptr += nlen;
  19.         }

  20.         // free(strings);
  21.     }
  22.     else
  23.     {
  24.         printf ( "no stack information\n" );
  25.     }
  26.     printf ( "the core dump stack info:\n\n%s", stack_info);


  27.     return;
  28. }


2.Posix 正则表达式
  1. //编译正则表达式,成功返回0,失败返回错误码
  2. int regcomp(regex_t *preg, const char *regex, int cflags);
 //执行,pmatch与nmatch组合用来存储匹配的子串的位置.
  1. int regexec(const regex_t *preg, const char *string, size_t nmatch, regmatch_t pmatch[], int eflags);

  2. size_t regerror(int errcode, const regex_t *preg, char *errbuf, size_t errbuf_size);

  3. void regfree(regex_t *preg);
示例代码:

  1. static int match(const char *str, const char *regexp)
  2. {
  3.     if ((!str) || (!regexp))
  4.         return 0;
  5.     
  6.     int ret = 0;
  7.     regex_t reg;
  8.     static const int flag = REG_EXTENDED | REG_ICASE | REG_NEWLINE;
  9.     static char errbuf[128];
  10.     int res = regcomp(&reg, regexp, flag);
  11.     if (res) {
  12.         regerror(res, &reg, errbuf, sizeof(errbuf));
  13.         printf("compile the [%s] failed for %s\n", regexp, errbuf);
  14.         goto out;
  15.     }
  16.     
  17.     regmatch_t matches[4];
  18.     res = regexec(&reg, str, 4, matches, 0);
  19.     if (!res) {
  20.         regmatch_t *mp = &matches[0];
  21.         while (mp->rm_so != -1)
  22.         {
  23.             int k = 0;
  24.             for (k = mp->rm_so; k < mp->rm_eo; ++k)
  25.             {
  26.                 putchar(str[k]);
  27.             }
  28.             printf ( "\n" );
  29.             ++mp;
  30.         }
  31.         ret = 1;
  32.         printf ( "match\n" );
  33.     }
  34.     else
  35.         printf ( "doesn't match\n" );

  36. out:
  37.     regfree(&reg);
  38.     return ret;
  39. }






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