如何在 C 程序中设置命令行参数,以便在用户键入“ps aux"时可见? [英] How do I set the command line arguments in a C program so that it's visible when users type "ps aux"?
问题描述
当您键入ps aux"时,ps 命令会显示程序运行时使用的命令参数.一些程序将其更改为指示状态的一种方式.我试过更改 argv[] 字段,但它似乎不起作用.是否有一种标准方法可以设置命令行参数,以便在用户键入 ps 时显示它们?
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
推荐答案
你的想法是对的,但你没有改变 argv[n]
中的 指针,你必须改变argv[0]
本身指向的字符串:
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;
}
(注意这是否真的改变了ps
显示的命令名称是系统相关的).
(Note that whether or not this actually changes the command name shown by ps
is system-dependent).
这篇关于如何在 C 程序中设置命令行参数,以便在用户键入“ps aux"时可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!