Change process name in Linux

前端 未结 5 2068
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 21:50

I\'m on Linux and I am forking/execing a new process out of my C spawn application. Is it possible to also change the naming of these new child processes?

I want to

5条回答
  •  [愿得一人]
    2021-01-03 22:08

    This is a non-portable hack:

    /*
     * Sets process title, truncating if there is not enough space, 
     * rather than causing memory corruption.
     */
    void set_title_np(int argc, char **argv, const char *title) {
        // calculate available size
        size_t space = 0;
        for (int i = 0; i < argc; i++) {
            size_t length = strlen(argv[i]);
            space += length + 1; // because of terminating zero 
        }
        memset(argv[0], '\0', space); // wipe existing args
        strncpy(argv[0], title, space - 1); // -1: leave null termination, if title bigger than space
    } 
    

提交回复
热议问题