Linux复习3——C语言编程实例

//文件资源限制, getrlimit()函数

//系统的资源限制范例实现需要的头文件

#include <sys/resource.h>
#include <sys/types.h>
#include <sys/time.h>
//下面这个库中有一个_exit()函数
#include <unistd.h>
#include <stdio.h>
//下面这个库中有exit()函数,exit(0)表示进程正常结束,而1表示异常退出
#include <stdlib.h>
//当时出现错误的原因应该是因为没有引入这个头文件,所以exit()不能被识别
#include <math.h>
/*work()函数将一个字符串写入临时文件10000次
然后通过一些算术运算形成CPU负载*/
void work(){
FILE *f;
int i;
double x=4.5;
//创建临时文件并打开
f=tmpfile();
for(i=0;i<10000;i++){
if(ferror(f))
{
fprintf(stderr, "Error of writing to the temporary file\n");
exit(1);
}
}
for(i=0;i<1000000;i++)
//通过复杂计算消耗大量CPU资源
x=log(x*x+3.21);
}

/*main()函数调用work()函数,然后用getrusage()函数来
获取程序耗费的CPU时间,并在屏幕上显示*/
int main(int argc, char const *argv[])
{
struct rusage r_usage;
struct rlimit r_limit;
int priority;
work();
//资源使用情况get resource usage
getrusage(RUSAGE_SELF,&r_usage);
printf("CPU usage: User=%1d.%061d,System=%1d.%061d\n",
r_usage.ru_utime.tv_sec,r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec,r_usage.ru_stime.tv_usec);
//调用getpriority()和getrlimit(),来获取当前优先级和文件限制大小
priority=getpriority(PRIO_PROCESS,getpid());
printf("Current priority=%d\n",priority);
//资源限制情况get resource limit
getrlimit(RLIMIT_FSIZE,&r_limit);
printf("Current FSIZE limit: soft=%ld,hard=%ld\n",
r_limit.rlim_cur,r_limit.rlim_max);
/*调用setrlimit()修改文件大小限制,并再次调用work(),
这次work()调用会失败。*/
r_limit.rlim_cur=2048;//单位为bytes,也就是2k
r_limit.rlim_max=4096;//也就是4kb
printf("Setting a 2K file size limit\n");
setrlimit(RLIMIT_FSIZE,&r_limit);
//再次调用work();
work();
//return 0;
exit(0);

}

//与终端进行交互,显示一个菜单,使用户与之进行交互

#include <stdio.h>
#include <stdlib.h>

/*程序开始部分定义一个用来显示菜单内容的字符数组
和getchoice函数的原型*/
char * menu[]={
"a - add a new record",
"d - delete a record",
"q - quit",
NULL
};
/*负责显示菜单及读取用户输入的函数getchoice()*/
int getchoice(char * greeet,char * choices[])
{
int chosen=0;
int selected;
/*刚刚查了一下,和预想的差不多,就是指针的指针
也就是存放了option地址的变量的地址
比如字符变量a的存储地址为500,那么*a的值为500,而
*a的地址为1000,所以**a为1000*/
char **option;
do{
printf("Choice:%s\n",greeet);
option=choices;
while(*option){
printf("%s\n",*option);
option++;
}
//getchar()是实现什么功能的函数??
selected=getchar();
option=choices;
while(*option){
if(selected==*option[0]){
chosen=1;
break;
}
option++;
}
if(!chosen){
printf("Incorrect choice,select again\n");
}
}while(!chosen);
return selected;
}
//main函数调用getchoice函数,完成菜单功能
int main(int argc, char const *argv[])
{
int choice=0;
do
{
choice=getchoice("Please select an action",menu);
printf("You have chosen:%c\n",choice );
}while(choice!='q')


return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值