tags:

views:

57

answers:

1

When you type "ps aux" the ps command shows command arguments that the program was run with. Some programs change this as a way of indicating status. I've tried changing argv[] fields and it doesn't seem to work. Is there a standard way to set the command line arguments so that they appear when the user types ps?

That is, this doesn't work:

int main(int argc,char **argv)
{
    argv[0] = "Hi Mom!";
    sleep(100);
}

09:40 imac3:~$ ./x &
[2] 96087
09:40 imac3:~$ ps uxp 96087 
USER      PID  %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND
yv32      96087   0.0  0.0  2426560    324 s001  S     9:40AM   0:00.00 ./x
09:40 imac3:~$ cat x.c
+2  A: 

You had the right idea, but you don't change the pointers in argv[n], you must change the string pointed to by argv[0] itself:

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

int main(int argc,char **argv)
{
    size_t maxlen = strlen(argv[0]);

    memset(argv[0], 0, maxlen);
    strncat(argv[0], "Hi Mom!", maxlen);
    pause();

    return 0;
}

(Note that whether or not this actually changes the command name shown by ps is system-dependent).

caf
Very strange use of `strncat`...
R..
@R..: No it's not. Combined with `strlen`, @caf is making a very careful observation that we might not be guaranteed to have more space than the original `argv[0]` to store our program name. Also, the `memset` isn't necessary, `strncat` will always null terminate. Very clean answer, nice use of `pause()`.
Matt Joiner
Look again. `strncat` is being used to concatenate to a zero-length string, i.e. as a cheap `strlcpy` instead of for actual concatenation. The `memset` is unnecessary, but you'd at least need `argv[0][0]=0;` to replace it for the desired functionality. This nonobviousness is why I said it's strange.
R..
The `memset()` *is* necessary due to the strange way that UNIX kernels traditionally treat the argument area.
caf
@R.. I stand corrected, @caf Strange indeed...
Matt Joiner
Wow. I didn't realize that strncat had different semantics than strncpy. They are both broken and people should use strlcpy and strlcat.
vy32