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

发布时间:2024年01月04日

参考:

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 <stdio.h>
#include <stdlib.h>
#include <sys/prctl.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>

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);
}

文章来源:https://blog.csdn.net/ykun089/article/details/135382852
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。