How do I set the command line arguments in a C program so that it's visible when users type "ps aux"?
Asked Answered
K

1

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
Kermanshah answered 21/9, 2010 at 13:41 Comment(2)
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.Mediterranean
Not possible? ( steve.org.uk/Reference/Unix/faq_2.html#SEC22 ) You might also like ( netsplit.com/2007/01/10/hiding-arguments-from-ps )Hughs
C
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).

Casady answered 21/9, 2010 at 14:0 Comment(6)
@R..: No it's not. Combined with strlen, @Casady 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().Metabolic
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.Irrepressible
@Kermanshah Not really broken, just misused, misunderstood and their rationale long forgotten...Styx
@Kermanshah - The UB happens only if you misuse the not null-terminated char arrays. But if that is what you need, then all is well.Styx
@vy32: ...and strncat() always null-terminates its result, anyway.Casady
@caf, you are right, strncat() and strncpy() differ in that manner. These inconsistencies are quite annoying. I'll remove my comment.Kermanshah

© 2022 - 2024 — McMap. All rights reserved.