Using prctl PR_SET_NAME to set name for process or thread?

13,110

Solution 1

Yes, you may use PR_SET_NAME in the first argument and the name as the second argument to set the name of the calling thread(or process). prctl returns 0 on success. Remember, it depends where you call this prctl. If you call it inside your process, it will change the name of that process and all of its belonging threads. If you call it inside a specific thread, it will change only the name of that thread.

Example:

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

Now, if you are running your process in Linux, type:

top

or

ps

To see the name attached to your process id.

Solution 2

Try the following code:

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));
}
Share:
13,110
ratzip
Author by

ratzip

Updated on June 14, 2022

Comments

  • ratzip
    ratzip almost 2 years

    I am trying to use prctl( PR_SET_NAME, "procname", 0, 0, 0) to set name for a process, when I am reading the Linux Manual about the PR_SET_NAME, looks like it set the name for thread if I understand it correctly.

    Can prctl be used to set name for process? How to set name for process?