Using prctl PR_SET_NAME to set name for process or

2020-02-28 21:12发布

问题:

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?

回答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.



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


回答3:

To set the process name you can use as you did prctl but that will show up only in /proc/pid/status (and programs using it). ps and top look elsewhere and to change the process name shown in ps and top, you must just change argv[0].

so just assigning it as argv[0]="newprocessname"; wil do.