Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change process name in Linux

Tags:

I'm on Linux and I am forking/execing a new process out of my C spawn application. Is it possible to also change the naming of these new child processes?

I want to be able to identify the process being started in case something goes wrong and I need to kill it manually. Currently they all have the same name.

like image 242
Frank Vilea Avatar asked May 21 '11 13:05

Frank Vilea


People also ask

How do you rename a Linux process?

Select a process. Right-click on the process and select the Rename option.

What is process name in Linux?

The process identifier (process ID or PID) is a number used by Linux or Unix operating system kernels. It is used to identify an active process uniquely.

How do I find the PID process name?

In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column. Click on any column name to sort. You can right click a process name to see more options for a process.


2 Answers

I think this should work, to illustrate the principle...

#include <stdio.h>

int main(int argc, char *argv[]) {
  argv[0][0] = 65;
  sleep(10);
}

will change the name, and put an "A" instead of the first letter. CtrlZ to pause, then run ps to see the name changed. I have no clue, but it seems somewhat dangerous, since some things might depend on argv[0].

Also, I tried replacing the pointer itself to another string; no cigar. So this would only work with strcpy and strings shorter or equal than the original name.

There might or might not be a better way for this. I don't know.

EDIT: nonliteral solution: If you're forking, you know the child's PID (getpid() in the child, result of fork() in the parent). Just output it somewhere where you can read it, and kill the child by PID.

another nonliteral solution: make softlinks to the executable with another name (ln -s a.out kill_this_a.out), then when you exec, exec the link. The name will be the link's name.

like image 67
Amadan Avatar answered Oct 03 '22 19:10

Amadan


According to this comment, prctl(PR_SET_NAME) only affects the "short name" of a thread. It has the same effect as writing into /proc/self/comm.

To change the "long name" (/proc/self/cmdline which is actually used by htop and ps u) you need some ugly hack (which is mentioned in that comment but the link is dead). An example of this kind of hack can be found in Chromium source code: https://source.chromium.org/chromium/chromium/src/+/master:content/common/set_process_title_linux.cc

like image 28
hexchain Avatar answered Oct 03 '22 21:10

hexchain