「C/C++」プロセス表示名前を設置する方法

サンプルコード:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

/* example
* ./a.out start
* memory layout, supporse ptr point to it
* ./a.out\0start\0HOSTNAME=vbloger\0TERM=linux\0
* argc = 2;
* argv[0] = ptr;
* argv[1] = ptr + strlen(argv[0])+1;
* argv[2] = 0;
* environ[0] = ptr + strlen(argv[0])+1 + strlen(argv[1])+1
* environ[1] = ptr + strlen(argv[0])+1 + strlen(argv[1])+1 + strlen(environ[0])+1
* environ[2] = 0;
*/

extern char **environ;
char *last;
/*プロセスタイトルを初期化*/
void initProcTitle(int argc, char **argv)
{
size_t size = 0;
for (int i = 0; environ[i]; ++i) {
size += strlen(environ[i])+1;
}

char *raw = new char[size];
for (int i = 0; environ[i]; ++i) {
memcpy(raw, environ[i], strlen(environ[i]) + 1);
environ[i] = raw;
raw += strlen(environ[i]) + 1;
}

last = argv[0];
for (int i = 0; i < argc; ++i) {
last += strlen(argv[i]) + 1;
}
for (int i = 0; environ[i]; ++i) {
last += strlen(environ[i]) + 1;
}
}
/*プロセスタイトルを設定*/
void setProcTitle(int argc, char **argv, const char *title)
{
argv[1] = 0;
char *p = argv[0];
memset(p, 0x00, last – p);
strncpy(p, title, last – p);
}
/*main 関数*/
int main(int argc, char *argv[])
{
initProcTitle(argc, argv);
setProctitle(argc, argv, “master so much argument can you believe");
sleep(30); //
return 0;
}

Development

Posted by arkgame