[Linux c/c++] 关于进程名,线程名,/proc文件系统 等

参考:

kernel - Why is the name of a process in /proc/PID/status not matching package name or ps command - Stack Overflowicon-default.png?t=N7T8https://stackoverflow.com/questions/14176058/why-is-the-name-of-a-process-in-proc-pid-status-not-matching-package-name-or-ps

设置和查看线程名:

#include 
#include 
#include 
#include 
#include 
#include 

void* thread1(void* a)
{
  prctl(PR_SET_NAME,"THREAD1");
  while(1) sleep(1000);
}

void* thread2(void* a)
{
  prctl(PR_SET_NAME,"THREAD2");
  while(1) sleep(1000);
}

int main()
{

  pthread_t th1,th2;
  pthread_create(&th1,NULL,thread1,NULL);
  pthread_create(&th2,NULL,thread2,NULL);


  char name[1024]={0};


  prctl(PR_GET_NAME, (unsigned long)name);
  printf("prctl api %s\n", name);
  memset(name,0,sizeof(name));
  pthread_getname_np(pthread_self(), name, 1024);
  printf("pthread api %s\n", name);

  int ret = prctl(PR_SET_NAME,"THREADMAIN");
  printf("-------ret=%d\n",ret);

  memset(name,0,sizeof(name));
  prctl(PR_GET_NAME, (unsigned long)name);
  printf("prctl api %s\n", name);
  memset(name,0,sizeof(name));
  pthread_getname_np(pthread_self(), name, 1024);
  printf("pthread api %s\n", name);


//
  printf("/\n");

  memset(name,0,sizeof(name));
  prctl(PR_GET_NAME, (unsigned long)name);
  printf("prctl api %s\n", name);
  memset(name,0,sizeof(name));
  pthread_getname_np(pthread_self(), name, 1024);
  printf("pthread api  %s\n", name);

  int rc = pthread_setname_np(pthread_self(), "xxxx");
  printf("-------rc=%d\n",rc);

  memset(name,0,sizeof(name));
  prctl(PR_GET_NAME, (unsigned long)name);
  printf("prctl api %s\n", name);
  memset(name,0,sizeof(name));
  pthread_getname_np(pthread_self(), name, 1024);
  printf("pthread api  %s\n", name);




  while(1) sleep(1000);
}

你可能感兴趣的:(#,Common/Linux,C/C++,linux,运维,服务器)