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

血红的双手。 提交于 2019-11-30 15:57:46

问题


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

回答1:


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).



来源:https://stackoverflow.com/questions/3760896/how-do-i-set-the-command-line-arguments-in-a-c-program-so-that-its-visible-when

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!