1. 得到进程ID - pid
#include <unistd.h> int pid = (int)getpid();std::cout<<"pid: "<<getpid()<<"\n";
C++ 打印pid和tid_shuai_wow的博客-CSDN博客_c++ 打印pid获取pid1. 包含头文件#include <unistd.h>2. 在需要打印pid的地方加入std::cout << "pid = " << getpid() << std::endl;获取tid1. 包含头文件#include <thread>2. 在需要打印tid的地方加入std::co...https://blog.csdn.net/u013431916/article/details/90033208
[check result]
Terminal 输出pid结果
htop 输出中对应程序的pid一致
2. 根据pid, 通过renice指令调高CPU优先级
//PART I Run Terminal CMD in cpp ref: https://zhuanlan.zhihu.com/p/351712885
using namespace std;
#define CMD_RESULT_BUF_SIZE 1024/** cmd:待执行命令* result:命令输出结果* 函数返回:0 成功;-1 失败;*/
int ExecuteCMD(const char *cmd, char *result)
{int iRet = -1;char buf_ps[CMD_RESULT_BUF_SIZE];char ps[CMD_RESULT_BUF_SIZE] = {0};FILE *ptr;strcpy(ps, cmd);if((ptr = popen(ps, "r")) != NULL){while(fgets(buf_ps, sizeof(buf_ps), ptr) != NULL){strcat(result, buf_ps);if(strlen(result) > CMD_RESULT_BUF_SIZE){break;}}pclose(ptr);ptr = NULL;iRet = 0; // 处理成功}else{printf("popen %s error\n", ps);iRet = -1; // 处理失败}return iRet;
}
/** 输入: 执行命令* 输出: 命令执行结果字符串*/
__inline std::string SystemWithResult(const char *cmd)
{char cBuf[CMD_RESULT_BUF_SIZE] = {0};string sCmdResult;ExecuteCMD(cmd, cBuf);sCmdResult = string(cBuf); // char * 转换为 string 类型printf("CMD Result: \n%s\n", sCmdResult.c_str());return sCmdResult;
}//PART II Run Terminal CMD in cpp ref: https://zhuanlan.zhihu.com/p/351712885int pid = (int)getpid();
string cpu_priority_up_cmd = "sudo renice -20 "; //priority range: 19 (lowest) ~ -20 (highest)
cpu_priority_up_cmd += to_string(pid);
cpu_priority_up_cmd += " -u ningxi root";
ROS_INFO_STREAM("pid = " << getpid()<<"). Run: "<<cpu_priority_up_cmd<<endl);
SystemWithResult(cpu_priority_up_cmd.data());
https://linux.die.net/man/2/setpriorityThe scheduling priority of the process, process group, or user, as indicated by which and who is obtained with the getpriority() call and set with the setpriority() call.https://linux.die.net/man/2/setprioritygetpriority(2) - Linux man pageThe getpriority() call returns the highest priority (lowest numerical value) enjoyed by any of the specified processes. The setpriority() call sets the ...
https://linux.die.net/man/2/getpriority
[check result]
如下则成功更改了 CPU优先级
测试环境:ubuntu18.04