Linux C/C++ gets the process number, thread number and sets the thread name

1 Introduction

During the Linux development process, when designing multi-threaded development, you can print out the IDs of processes and threads to facilitate development, debugging and later troubleshooting. It also includes setting the thread name.

2 Functions and header files

2.1 Process ID

#include <unistd.h>

pid_t getpid(void);

2.2 Thread ID

In Linux, each process has a pid, type pid_t, which is obtained by getpid() . POSIX threads under Linux also have an id, type pthread_t, obtained by pthread_self(). The id is maintained by the thread library, and its id space is independent of each process (that is, threads in different processes may have the same id). The thread implemented by the POSIX thread library in Linux is actually a process (LWP), but the process only shares some resources with the main process (the process that starts the thread), such as code segments, data segments, etc.

Since gettid() does not implement this function in glibc, we can implement it ourselves through the Linux system call syscall

#include <sys/unistd.h>

#define gettid() syscall(__NR_gettid)

/* 第二种 */
#include <sys/syscall.h>

#define gettid() syscall(SYS_gettid)  // #define SYS_gettid __NR_gettid 在 sys/syscall.h 中定义

When there is only one thread, the pid is returned.

2.3 Set thread name

#include <prctl.h>

prctl(PR_SET_NAME, "testThread"); 

// 可以通过设置 PR_GET_NAME 获取当前线程的名字

2.4 Example

Need to be called in thread function

#include <sys/prctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <thread>
#include <stdio.h>
#include <string.h>

#define gettid() syscall(SYS_gettid)

void TestThreadBody(int threadNumber)
{
    char szThreadName[20];

    snprintf(szThreadName, 20, "testThread-%d", threadNumber);
    prctl(PR_SET_NAME, szThreadName); 

    memset(szThreadName, 0, 20);
    prctl(PR_GET_NAME, szThreadName); 

    printf("Thread[%s] pid:%u, tid:%u\n", szThreadName, (unsigned int)getpid(), (unsigned int)gettid());
}

int main()
{
    char szThreadName[20];
    prctl(PR_SET_NAME, "mainThread"); 
    prctl(PR_GET_NAME, szThreadName); 
    printf("Thread[%s] pid:%u, tid:%u\n", szThreadName, (unsigned int)getpid(), (unsigned int)gettid());

    std::thread(TestThreadBody, 1).detach();
    std::thread(TestThreadBody, 2).detach();
    std::thread(TestThreadBody, 3).detach();

    return 0;
}

Original link: "Link"

Original link

Linux C/C++ Gets the process number, thread number and sets the thread name - QT Development Chinese Network Linux C/C++ Gets the process number, thread number and sets the thread name https://qt.0voice.com/?id=1006

Guess you like

Origin blog.csdn.net/QtCompany/article/details/130225335