跳到主要内容

Linux 设置线程名称

方法一

int s;
s = prctl(PR_SET_NAME,"myProcess\0",NULL,NULL,NULL); // name: myProcess

方法二

pthread_setname_np(pthread_self(), "parseInsData"); 
const char *newName = "newname";
char *baseName;

// find application base name to correct
char *appName = const_cast<char *>(argv[0]);
if (((baseName = strrchr(appName, '/')) != NULL ||
(baseName = strrchr(appName, '\\')) != NULL) && baseName[1]) {
appName = baseName + 1;
}

// Important! set new application name inside existing memory block.
// we want to avoid argv[0] = newName; because we don't know
// how cmd line buffer will be released during application shutdown phase
// Note: new process name has equal or shorter length than current argv[0]
size_t appNameLen;
if ((appNameLen = strlen(appName)) != 0) {
strncpy(appName, newName, appNameLen);
appName[appNameLen] = 0;
}

// set new current thread name
if (prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(const_cast<char *>(newName)), NULL, NULL, NULL)) {
Log::error("prctl(PR_SET_NAME, \"%s\") error - %s", newName, strerror(errno));
}