2014-04-30 3 views
0

'ps'가 프로세스의 CMD 이름으로 표시되도록 프로그램을 변경하려고합니다. 가리킨 메모리를 오버레이하는 것이 좋습니다 argv [0]에 의해. 여기 제가 작성한 샘플 프로그램이 있습니다.argv [0]을 변경하여 Linux 'ps'출력 변경

#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) {}; 
} 

출력은 다음과 같습니다

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

는 "foo는"삽입 있지만 null 종결 중 하나를 무시하거나 켠 :

$ ./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. 

추신 -ef의 출력은 공백으로 원본 argv [0]의 뒷 부분은 여전히 ​​표시됩니다.

어떻게하면 'ps'가 인쇄하는 문자열로 바꿀 수 있습니까?

+0

장의'/ proc 디렉토리/$ PID/cmdline' 특수 파일 안에 무엇? 그것의'hexdump -C' 할 수 있습니까? – osgx

+0

00000000 66 6f 6f 00 5f 74 65 73 74 00 66 6f 6f 00 62 61 | foo._test.foo.ba | 00000010 72 00 | r. | – Chap

+0

@osgx : 제대로 포맷 할 수는 없지만 아래의 tetromino의 설명과 일치합니다. – Chap

답변

2

전체 명령 줄을 다시 작성해야합니다.이 명령 줄은 인수가 0으로 분리 된 연속 버퍼로 저장됩니다. 같은

뭔가 :

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); 
+1

올바른 것으로 보입니다. 그리고 argv [1..n]가 null로 끝나는 인수를 가리키고 있다는 것을 확인했습니다. 이는 argv [1..n]을 clawbering하는 것을 의미합니다. 알고 있어야 할 것. – Chap