在linux上更改线程名称(htop)

Gae*_*ola 14 c linux pthreads

我有一个多线程应用程序,我希望htop(例如)每个运行的线程显示一个不同的名称,此时显示的是用于运行main的"命令行".

我试过用

prctl(PR_SET_NAME, .....)
Run Code Online (Sandbox Code Playgroud)

但它只适用于顶部,并且只有该调用才能指定最多16个字节的名称.

我想诀窍是修改/ proc/PID/cmdline内容,但这是一个只读字段.

谁知道如何实现它?

Dre*_*kes 20

从版本0.8.4开始,htop有一个选项:显示自定义线程名称

按,F2然后选择Display options菜单.你应该看到:

htop自定义线程名称


llo*_*ngi 5

您必须在此处区分每线程和每个进程设置.

prctl(PR_SET_NAME,...)在每个线程的基础上设置名称(最多16个字节),您可以强制"ps"用c开关显示该名称(例如ps Hcx).您可以使用顶部的c开关执行相同的操作,因此我假设htop具有类似的功能.

什么"ps"通常显示你(例如ps Hax)是你启动程序的命令行名称和参数(实际上是/ proc/PID/cmdline告诉你的),你可以通过直接修改argv [0]来修改它们. (达到其原始长度),但这是一个按进程设置,这意味着你不能用不同的线程给出不同的名称.

以下是我通常用来更改整个流程名称的代码:

// procname is the new process name
char *procname = "new process name";

// Then let's directly modify the arguments
// This needs a pointer to the original arvg, as passed to main(),
// and is limited to the length of the original argv[0]
size_t argv0_len = strlen(argv[0]);
size_t procname_len = strlen(procname);
size_t max_procname_len = (argv0_len > procname_len) ? (procname_len) : (argv0_len);

// Copy the maximum
strncpy(argv[0], procname, max_procname_len);
// Clear out the rest (yes, this is needed, or the remaining part of the old
// process name will still show up in ps)
memset(&argv[0][max_procname_len], '\0', argv0_len - max_procname_len);

// Clear the other passed arguments, optional
// Needs to know argv and argc as passed to main()
//for (size_t i = 1; i < argc; i++) {
//  memset(argv[i], '\0', strlen(argv[i]));
//}
Run Code Online (Sandbox Code Playgroud)

  • 提交者要求每线程设置,不是吗? (2认同)