How do I set the command line arguments in a C program so that it's visible when users type "ps aux"?
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 arg开发者_Go百科v[] 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
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).
精彩评论