APUE2e之Exercise 10.11

来源:互联网 发布:知天下图吧 编辑:程序博客网 时间:2024/06/10 00:32
/**    * apue-chap10: exercise10-11.c * * Description: TODO * * Created On: Mar 1, 2012  * * @author: Huang Zhu * * @email: zhuhuang.zp@gmail.com */ //Run under Ubuntu 10.04. sig_intr is not called.//But write returns a count of 24 when the destination file size reaches 1024 bytes. #include <apueerr.h>#include <fcntl.h>#include <sys/resource.h> #define BUFFSIZE 100//SIGXFSZ//signal_intr static void sig_intr(int signo){printf("Signal handler sig_intr is called!\n");} int main(int argc, char* argv[]){int n, w;char buf[BUFFSIZE];int fd1, fd2;struct sigaction act, oact;struct rlimit olimit, nlimit; if(argc < 3){printf("Copy contents from one file to another...\n");err_sys("Usage: ./a.out src dest");} if((fd1 = open(argv[1], O_RDONLY, 0)) < 0)err_sys("open error: %s doesn't exist", argv[1]);if((fd2 = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) < 0)err_sys("open error: cannot open or create file %s!", argv[2]); act.sa_handler = sig_intr;sigemptyset(&act.sa_mask);act.sa_flags = 0;if(sigaction(SIGXFSZ, &act, &oact) < 0)err_sys("sigaction SIGXFSZ error!"); if(getrlimit(RLIMIT_FSIZE, &olimit) != 0) //get resource limiterr_sys("getrlimit RLIMIT_FSIZE error!");printf("Current soft limit for RLIMIT_FSIZE: %d\n", (int)olimit.rlim_cur); printf("Set RLIMIT_FSIZE to 1024!\n"); nlimit.rlim_cur = 1024;nlimit.rlim_max = olimit.rlim_max;if(setrlimit(RLIMIT_FSIZE, &nlimit) != 0) //set resource limiterr_sys("setrlimit RLIMIT_FSIZE error!"); if(getrlimit(RLIMIT_FSIZE, &olimit) != 0)err_sys("getrlimit RLIMIT_FSIZE error!");printf("Current soft limit for RLIMIT_FSIZE: %d\n", (int)olimit.rlim_cur);     while ((n=read(fd1, buf, BUFFSIZE))>0)        if((w = write(fd2, buf, n))!=n){        printf("write error: %d bytes were written!\n", w);        break;        }    if(n<0)      err_sys("read error: %d bytes read from file %s!\n", n, argv[1]);    sigaction(SIGXFSZ, &oact, NULL); //reset signal handler back to default   if(setrlimit(RLIMIT_FSIZE, &olimit) != 0) //reset resource limit back to default   err_sys("setrlimit RLIMIT_FSIZE error!");   exit(0);}

原创粉丝点击