5

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
SamB
  • 9,039
  • 5
  • 49
  • 56
vy32
  • 28,461
  • 37
  • 122
  • 246
  • I think ythis is some kind of thing called "bash tab extension". You need to define a tab extension handler for your program and register it in some file, but don't ask me how to do this. – fuz Sep 21 '10 at 13:46
  • Not possible? ( http://www.steve.org.uk/Reference/Unix/faq_2.html#SEC22 ) You might also like ( http://www.netsplit.com/2007/01/10/hiding-arguments-from-ps/ ) – pmg Sep 21 '10 at 13:54

1 Answers1

5

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
  • 233,326
  • 40
  • 323
  • 462
  • @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 Sep 21 '10 at 16:14
  • 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.. GitHub STOP HELPING ICE Sep 21 '10 at 17:06
  • 1
    @vy32 Not really broken, just misused, misunderstood and their rationale long forgotten... – rodrigo Feb 11 '12 at 21:22
  • @vy32 - The UB happens only if you misuse the not null-terminated char arrays. But if that is what you need, then all is well. – rodrigo Feb 12 '12 at 10:50
  • @vy32: ...and `strncat()` always null-terminates its result, anyway. – caf Feb 12 '12 at 12:10
  • @caf, you are right, `strncat()` and `strncpy()` differ in that manner. These inconsistencies are quite annoying. I'll remove my comment. – vy32 Feb 13 '12 at 11:53