change thread name on linux (htop)

前端 未结 2 653
悲哀的现实
悲哀的现实 2021-01-31 05:39

I have a multithread application and I would like that htop (as example) shows a different name per each thread running, at the moment what it shows is the \"command line\" used

相关标签:
2条回答
  • 2021-01-31 06:01

    Since version 0.8.4, htop has an option: Show custom thread names

    Press F2 and select the Display options menu. You should see:

    htop custom thread names

    0 讨论(0)
  • 2021-01-31 06:12

    You have to distinguish between per-thread and per-process setting here.

    prctl(PR_SET_NAME, ...) sets the name (up to 16 bytes) on a per-thread basis, and you can force "ps" to show that name with the c switch (ps Hcx for example). You can do the same with the c switch in top, so I assume htop has similar functionality.

    What "ps" normally shows you (ps Hax for example) is the command line name and arguments you started your program with (indeed what /proc/PID/cmdline tells you), and you can modify those by directly modifying argv[0] (up to its original length), but that is a per-process setting, meaning you cannot give different names to different threads that way.

    Following is the code I normally use to change the process name as a whole:

    // 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]));
    //}
    
    0 讨论(0)
提交回复
热议问题