Using prctl PR_SET_NAME to set name for process or thread?

前端 未结 3 1687
失恋的感觉
失恋的感觉 2021-01-02 17:14

I am trying to use prctl( PR_SET_NAME, \"procname\", 0, 0, 0) to set name for a process, when I am reading the Linux Manual about the PR_SET_NAME, looks like it

3条回答
  •  长情又很酷
    2021-01-02 17:23

    Try the following code:

    const char *newName = "newname";
    char *baseName;
    
    // find application base name to correct
    char *appName = const_cast(argv[0]);
    if (((baseName = strrchr(appName, '/')) != NULL ||
       (baseName = strrchr(appName, '\\')) != NULL) && baseName[1]) {
       appName = baseName + 1;
    }
    
    // Important! set new application name inside existing memory block.
    // we want to avoid argv[0] = newName; because we don't know
    // how cmd line buffer will be released during application shutdown phase
    // Note: new process name has equal or shorter length than current argv[0]
    size_t appNameLen;
    if ((appNameLen = strlen(appName)) != 0) {
        strncpy(appName, newName, appNameLen);
        appName[appNameLen] = 0;
    }
    
    // set new current thread name
    if (prctl(PR_SET_NAME, reinterpret_cast(const_cast(newName)), NULL, NULL, NULL)) {
        Log::error("prctl(PR_SET_NAME, \"%s\") error - %s", newName, strerror(errno));
    }
    

提交回复
热议问题