lowlevellock.S fopen和pthread

时间:2016-07-06 23:50:32

标签: pthreads fopen

我试图通过直接从/ proc / self / statm伪系统文件访问此信息来监视应用程序的内存使用情况。 不幸的是,读取statm文件会使我的应用程序挂起以下跟踪:

(gdb) bt
 #0  0xb7fdd424 in __kernel_vsyscall ()
 #1  0xb781ddc1 in __lll_lock_wait_private () at ../nptl/sysdeps/unix/sysv/linux/i386/i686/../i486/lowlevellock.S:97
 #2  0xb779d65a in _L_lock_11087 () from /lib/i386-linux-gnu/libc.so.6
 #3  0xb779b34d in __GI___libc_malloc (bytes=12) at malloc.c:2887
 #4  0xb799ea47 in operator new(unsigned int) () from /usr/lib/i386-linux-gnu/libstdc++.so.6

这是一个已知问题,是否有一些可以建议的解决方法? 我被建议实施基于线程的解决方案,但同样,我遇到了同样的问题。 我欢迎任何关于如何解决这个问题的建议。 感谢。

下面,我发布了基于pthread bu的方法,该方法也失败了:

typedef struct {
   int pid;
   int value;
} pthread_param_t;

//---------------------------------
void* memoryUsage(void* argv){
  pthread_param_t* param= (pthread_param_t*)argv;
  //
  //usleep(500000);
  // don't ignore cancel requests
  pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
  char s[125];
  sprintf(s,"/proc/%d/statm",param->pid);
  FILE* fp = fopen(s,"r");
  if ( fp != NULL ) {
    int rss = 0;
    if ( fscanf( fp, "%*s%d", &rss ) == 1 ){
       param->value=(int)rss * (int)sysconf(_SC_PAGESIZE);
    }
    fclose( fp );
   }
   return NULL;
}

//---------------------------------
int getUsedMemory(){
   pthread_param_t* param= new pthread_param_t;
   param->pid = getpid();
   param->value = -1;
   pthread_t thr;
   pthread_create(&thr,NULL,&memoryUsage, (void*)param);
   // whatever happens, we wait 5 ms before cancelling the thread
   usleep(5000);
   pthread_cancel(thr);
   if (pthread_cancel(thr) == ESRCH){
    printf("Memoire (ERROR)\n");
   }
   int s =param->value;
   delete param;
   return s;
}
//---------------------------------
int main (){
  for (int i=0; i<1000; ++i){
    printf("allocated memory = %d\n", getUsedMemory());
  }
 return 0;
}

我想知道我是否可以使用更聪明的方法。 感谢您的宝贵帮助,

0 个答案:

没有答案