zoukankan      html  css  js  c++  java
  • Linux环境资源限制例程

     1 #include <sys/types.h>
     2 #include <sys/resource.h>
     3 #include <sys/time.h>
     4 #include <unistd.h>
     5 #include <stdio.h>
     6 #include <math.h>
     7 
     8 void work()
     9 {
    10     FILE *f;
    11     int i;
    12     double x=4.5;
    13     f=tmpfile();
    14     for(i=0;i<10000;i++);
    15     {
    16         fprintf(f,"Do some output
    ");//将一个字符串写入临时文件10000
    17         if(ferror(f))
    18         {
    19             fprintf(stderr,"Error writing to temporary file
    ");
    20             exit(1);
    21         }
    22     }//完成
    23     for (i=0;i<1000000;i++)
    24         x=log(x*x+3.21);//做一些算术运算
    25 }
    26 
    27 int main()
    28 {
    29     struct rusage r_usage;
    30     struct rlimit r_limit;
    31     int priority;
    32     
    33     work();
    34     getrusage(RUSAGE_SELF, &r_usage);//第一个参数代表仅返回当前程序的使用信息,保存在第二个参数中
    35     
    36     printf("CPU usage: User=%ld.%06ld,System=%ld.%06ld
    ",
    37     r_usage.ru_utime.tv_sec,r_usage.ru_utime.tv_usec,
    38     r_usage.ru_stime.tv_sec,r_usage.ru_stime.tv_usec);//打印出cpu消耗
    39     
    40     priority=getpriority(PRIO_PROCESS, getpid());
    41     printf("Current priority = %d
    ", priority);//获取当前优先级
    42     
    43     getrlimit(RLIMIT_FSIZE,&r_limit);//获取当前文件限制
    44     printf("Current FSIZE limit: soft=%ld, hard=%ld
    ",r_limit.rlim_cur,r_limit.rlim_max);
    45     
    46     r_limit.rlim_cur=2048;
    47     r_limit.rlim_max=4096;
    48     printf("Setting a 2k file size limit
    ");
    49     setrlimit(RLIMIT_FSIZE,&r_limit);
    50     
    51     work();
    52     exit(0);
    53 }

    运行效果

     1 jason@t61:~/c_program$ ./limits 
     2 CPU usage: User=0.056000,System=0.000000
     3 Current priority = 0
     4 Current FSIZE limit: soft=-1, hard=-1
     5 Setting a 2k file size limit
     6 jason@t61:~/c_program$ ulimit 
     7 unlimited
     8 jason@t61:~/c_program$ nice ./limits 
     9 CPU usage: User=0.060000,System=0.000000
    10 Current priority = 10
    11 Current FSIZE limit: soft=-1, hard=-1
    12 Setting a 2k file size limit

    万事走心 精益求美


  • 相关阅读:
    mysql mysqldump 本地数据库导入本地数据库的命令
    window mysql5.7 zip 安装
    MySQL存储过程详解 mysql 存储过程
    spring batch 读取多个文件数据导入数据库
    spring batch 以游标的方式 数据库读取数据 然后写入目标数据库
    不同浏览器上中文文件名的下载乱码问题
    spring mvc 文件下载 get请求解决中文乱码问题
    SpringMVC上传文件的三种方式
    NSPort
    iOS NSRunloop
  • 原文地址:https://www.cnblogs.com/kongchung/p/4603597.html
Copyright © 2011-2022 走看看