Change process name without changing argv[0] in Linux
Asked Answered
A

2

8

I need to modify the process name of my program in C language.
I precise, this is not the name of a thread that I want to change.
I want to change the name of my program, but the only solution I found, is to modify the value of argv[0].
I also found another solution with prctl(PR_SET_NAME, "newname"), but this solution doesn't work.

Adopted answered 23/4, 2013 at 9:24 Comment(3)
possible duplicate of How to name a thread in Linux?Invertase
"The documentation says PR_SET_NAME sets the process name; but that documentation is wrong - it does actually set the thread name. Now "top" and "ps -L" show the thread name." -- user9876 Apr 22 '09 at 17:39Invertase
PR_SET_NAME flag is supported since Linux 2.6.9Seitz
T
19

The differences between invoking prctl and modify argv[0] are:

  • modify argv[0] changes information in /proc/$pid/cmdline
  • invoking prctl(PR_SET_NAME) changes information in /proc/$pid/status

That means you will get difference name of your process issuing ps -a and ps -ax.

If you expects same process name for different arguments while executing ps, you can do them both (i.e., change argv[0] and invoke prctl).

Hope the answer helps.

Truthful answered 15/6, 2013 at 3:53 Comment(0)
D
-2

try this:

char *process_name = "aaa\0";
memcpy((void *)argv[0], process_name, sizeof(process_name));

/* explain: The space allocated for argv[0] could be smaller than the name that you want to give and then you will be overwritting some other unrelated memory. argv[0] size could be just 2 and if your process name is "averylongprocessname" you will be overflowing argv[0]. You need to strlen(argv[0]) and use that in memcpy. thx @ecerulm

*/

Demonography answered 5/3, 2014 at 11:29 Comment(5)
I think that the \0 is unnecessary - isn't it already silently appended to a literal string of characters?Brozak
@Chap: it's true for strcpy, not for memcpy.Leadsman
Seems that you have to overwrite all characters of origin argv[0], is it true? So you can't have process names bigger than original nameContributory
The space allocated for argv[0] could be smaller than the name that you want to give and then you will be overwritting some other unrelated memory. argv[0] size could be just 2 and if your process name is "averylongprocessname" you will be overflowing argv[0]. You need to strlen(argv[0]) and use that in memcpy.Sallee
The \0 is unnecessary. Also, sizeof is incorrect here as it would return the size of a pointer (typically 4 or 8 bytes). You want something more like strncpy(argv[0], process_name, strlen(process_name) or memcpy(argv[0], process_name, (strlen(argv[0]) < strlen(process_name)+1) ? strlen(argv[0]) : strlen(process_name)+1)Angiosperm

© 2022 - 2024 — McMap. All rights reserved.