本文基于unix环境高级编程的学习的笔记,写的比较简如有不对,欢迎指点。
简单的描述下面函数的功能改变ctr+c信号原本的作用终止程序,在按下中断键的时候输出一句话。
while循环主要读取用户的输入,根据用户的输入解析输入的命令之后调用exec函数执行命令
1 #include "apue.h" 2 #include <sys/wait.h> 3 4 void sig_int(int signo) 5 { 6 printf("interrup "); 7 } 8 9 int main(void) 10 { 11 char buf[MAXLINE]; 12 pid_t pid; 13 int status; 14 15 if(signal(SIGINT,sig_int) == SIG_ERR) 16 err_sys("signal error"); 17 18 19 printf("%%"); 20 while(fgets(buf,MAXLINE,stdin) != NULL){ 21 if(buf[strlen(buf) - 1] == ' ') 22 buf[strlen(buf) - 1] = 0; 23 if((pid = fork()) < 0){ 24 err_sys("fork error "); 25 }else if(pid == 0){ 26 execlp(buf,buf,(char *)0); 27 err_ret("couldn't execute:%s",buf); 28 exit(127); 29 } 30 31 if((pid = waitpid(pid,&status,0)) < 0) 32 err_sys("waitpid error"); 33 printf("%% "); 34 35 } 36 exit(0); 37 38 return 0; 39 }
运行情况如下:
1.10