《Linux程序设计 第四版》之第四章的练习题

1、P128

一个获取日期 时间 格式化获取时间 日期 的程序。

#include<stdio.h>#include<time.h>int main(int argc,char** argv){struct tm* time1,*time_trans; //时间数据结构time_t alt;char c_time[128];char* result;char* result1="";time(&alt);time1=localtime(&alt); //返回本地时间存到数据结构中printf("the date is %d.%d.%d \n",time1->tm_year,time1->tm_mon,time1->tm_mday); printf("the date is %s \n",ctime(&alt));//ctime将数据结构中转换成字符串返回strftime(c_time,128,"%Y %B %d %p %I:%M:%S",time1); //格式化将时间存到c_time字符串printf("%s\n", c_time);strcpy(c_time,"12 Mar 2008,12:13:14");printf("Now trans the time %s \n", c_time);result=strptime(c_time,"%d %b %Y,%R:%S",time_trans);printf("%s \n", result);//printf("%d", strcmp(result1,"ye"));if(strcmp(result,result1)==0){printf("%d %d %d\n", time_trans->tm_hour,time_trans->tm_min,time_trans->tm_sec);}return 0;}

2、P130、132

一个创建临时文件、获取用户信息、输出Log的程序。

#include<stdio.h>#include<pwd.h>#include<sys/types.h>#include<syslog.h>int main(int argc,char** argv){uid_t id;struct passwd *pw;FILE* tempFile;char* fileName;id=getuid();//获取用户的uidpw=getpwuid(id); //获取用户uid的pw文件信息printf("UID PASSWORD ENTRY:\n name=%s,uid=%d,home=%s,shell=%s\n",pw->pw_name,pw->pw_uid, pw->pw_dir,pw->pw_shell);pw=getpwnam("root"); //获取用户root的pw文件信息printf("ROOT PASSWORD ENTRY:\n name=%s,uid=%d,home=%s,shell=%s\n",pw->pw_name,pw->pw_uid, pw->pw_dir, pw->pw_shell);while(pw=getpwent()) //依次获取所有用户的pw文件信息{//printf("UID PASSWORD ENTRY:\n name=%s,uid=%d,home=%s,shell=%s\n",pw->pw_name,pw->pw_uid, pw->pw_dir, pw->pw_shell);}fileName=tmpnam((void*)0);//返回一个唯一的文件名tempFile=fopen(fileName,"r");if(!tempFile){syslog(LOG_ERR|LOG_USER,"oops-%m\n");}tempFile=tmpfile();//返回一个有唯一的文件名的文件file*if(!tempFile){syslog(LOG_ERR|LOG_USER,"%m\n");}return 0;}

3、P141

一个资源限制 CPU消耗的程序。

#include<stdio.h>#include<sys/time.h>#include<sys/types.h>#include<sys/resource.h>#include<math.h>void fun(){char* tmpStr="what's wrong \n";FILE* f;//f=fopen("haha","w+");f=tmpfile();int i=0;if (!f){printf("??\n");}for(;i<1000000;i++){fwrite(tmpStr, sizeof(tmpStr),1,f);if(ferror(f)){fprintf(stderr,"WRONG");return ;}}i=0;for (; i < 10000000; ++i){int k;k=(1.1+i*i);}//f.close();}int main(int argc,char** argv){struct rusage r_usage;struct rlimit r_limit;int pro;fun();getrusage(RUSAGE_SELF,&r_usage); //获得程序运行的信息 存到结构体rusage中printf("CPU usage: User=%d.%06d,system==%d.%06d\n",r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,r_usage.ru_stime.tv_sec,r_usage.ru_stime.tv_sec);pro=getpriority(PRIO_PROCESS,getpid()); //获得程序的优先级printf("Current Priority:%d\n",pro);r_limit.rlim_cur=2048;r_limit.rlim_max=4096;setrlimit(RLIMIT_FSIZE,&r_limit); //设置程序的一些资源限制fun();return 0;}

版权声明:本文为博主原创文章,未经博主允许不得转载。

,我们什么都没有,唯一的本钱就是青春。

《Linux程序设计 第四版》之第四章的练习题

相关文章:

你感兴趣的文章:

标签云: