使用getrlimit控制进程使用系统CPU
[cpp]#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <signal.h>
void sigxcpu_handler(int signum)
{
printf ("SIGXCPU Received!\n");
//可以在这里就退出进程 exit(1);
}
void sigkill_handler(int signum)
{
printf ("SIGKILL received!\n");
}
int main(void)
{
signal(SIGXCPU, sigxcpu_handler);
//无效的,kill信号不允许自定义
signal(SIGKILL, sigkill_handler);
struct rlimit rl;
int ret = getrlimit (RLIMIT_CPU, &rl);
if (ret == -1)
{
printf("Failed to getrlimit!\n");
exit(-1);
}
//进程使用cpu时间达到rlim_cur时,操作系统向进程发送SIGXCPU信号,如果进程未终止,则之后每秒发送一次
rl.rlim_cur = 1;
//进程使用CPU时间达到rlim_max时,操作系统向进程发送SIGKILL信号,终止进程
rl.rlim_max = 5;
ret = setrlimit (RLIMIT_CPU, &rl);
if (ret == -1)
{
printf("Failed to set limit.\n");
exit(-1);
}
while (1)
;
return 0;
}
补充:软件开发 , C++ ,