gpt4 book ai didi

linux - 通过更改 argv[0] 更改 Linux 'ps' 输出

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:57 24 4
gpt4 key购买 nike

我正在尝试让一个程序更改“ps”显示为进程的 CMD 名称的内容,使用我所推荐的技术来简单地覆盖 argv[0] 指向的内存。这是我写的示例程序。

#include <iostream>
#include <cstring>
#include <sys/prctl.h>
#include <linux/prctl.h>
using std::cout;
using std::endl;
using std::memcpy;

int main(int argc, char** argv) {
if ( argc < 2 ) {
cout << "You forgot to give new name." << endl;
return 1;
}

// Set new 'ps' command name - NOTE that it can't be longer than
// what was originally in argv[0]!

const char *ps_name = argv[1];
size_t arg0_strlen = strlen(argv[0]);
size_t ps_strlen = strlen(ps_name);
cout << "Original argv[0] is '" << argv[0] << "'" << endl;

// truncate if needed
size_t copy_len = (ps_strlen < arg0_strlen) ? ps_strlen+1 : arg0_strlen;
memcpy((void *)argv[0], ps_name, copy_len);
cout << "New name for ps is '" << argv[0] << "'" << endl;

cout << "Now spin. Go run ps -ef and see what command is." << endl;
while (1) {};
}

输出是:

$ ./ps_test2 foo
Original argv[0] is './ps_test2'
New name for ps is 'foo'
Now spin. Go run ps -ef and see what command is.

ps -ef 的输出是:

5079     28952  9142 95 15:55 pts/20   00:00:08 foo _test2 foo

显然,插入了“foo”,但它的空终止符要么被忽略,要么变成空白。原始 argv[0] 的尾部仍然可见。

如何替换“ps”打印的字符串?

最佳答案

您需要重写整个命令行,它在 Linux 中存储为一个连续的缓冲区,参数以零分隔。

类似于:

size_t cmdline_len = argv[argc-1] + strlen(argv[argc-1]) - argv[0];
size_t copy_len = (ps_strlen + 1 < cmdline_len) ? ps_strlen + 1 : cmdline_len;
memcpy(argv[0], ps_name, copy_len);
memset(argv[0] + copy_len, 0, cmdline_len - copy_len);

关于linux - 通过更改 argv[0] 更改 Linux 'ps' 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23398952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com