Setting the thread /proc/PID/cmdline?
Asked Answered
S

3

5

On Linux/NPTL, threads are created as some kind of process.

I can see some of my process have a weird cmdline:

cat /proc/5590/cmdline 
hald-addon-storage: polling /dev/scd0 (every 2 sec)

Do you have an idea how I could do that for each thread of my process? That would be very helpful for debugging.

Subordinary answered 26/9, 2008 at 14:25 Comment(0)
H
6

If you want to do this in a portable way, something that will work across multiple Unix variations, there are very few options available.

What you have to do is that your caller process must call exec with the argv [0] argument pointing to the name that you would like to see in the process output, and the filename pointing to the actual executable.

You can try this behavior from the shell by using:

exec -a "This is my cute name" bash

That will replace the current bash process with one named "This is my cute name".

For doing this in C, you can look at the source code of sendmail or any other piece of software that has been ported extensively and find all the variations that are needed across operating systems to support this.

Some operating systems have a setproctitle(3) API, some others allow you to override the contents of argv [0] and show that result.

Hoi answered 26/9, 2008 at 14:51 Comment(1)
PostgreSQL's implementation seems like a particularly sturdy one: github.com/postgres/postgres/blob/…Tai
M
5

argv points to writable strings. Just write stuff to them:

#include <string.h>
#include <unistd.h>

int
main(int argc, char** argv)
{
    strcpy(argv[0], "Hello, world!");
    sleep(10);
    return 0;
}
Marsden answered 26/9, 2008 at 14:39 Comment(4)
quite ugly, but I'll use that I guessSubordinary
this could potentially be a buffer overflow. Especially if your new string is longer than the original. You could likely be better off allocating a new string on the heap and assigning that to argv[0]Geest
Unfortunately, assigning to argv[0] doesn't do anything. That would, indeed, be my first preference.Marsden
And yes, it definitely is a buffer overflow. More serious ways to accomplish this (setproctitle() in util-linux, for example) actually relocate the environment to somewhere safe before overwriting it.Marsden
S
0

Bah.. the code is not that nice, the trick is to reuse the environ (here argv_buffer) pointer:

memset (argv_buffer[0] + len, 0, argv_size - len);
argv_buffer[1] = NULL;

Any better idea?

Is that working for different threads?

Subordinary answered 26/9, 2008 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.