得到c++程序Process ID [getpid()], 调高CPU优先级 [renice]

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/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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值