1. 得到进程ID - pid
#include <unistd.h>
int pid = (int)getpid();
std::cout<<"pid: "<<getpid()<<"\n";
[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/351712885
int 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