一、源代码
<bldc:/home/tingbinz/apue.2e/include/1>R*_*G:vim 1_8.c
1 #include "apue.h"
2 #include <sys/wait.h>
3
4 static void sig_int(int);
5
6 int main(void)
7 {
8 pid_t pid;
9 char buf[MAXLINE];
10 int status;
11
12 if( signal(SIGINT,sig_int) == SIG_ERR )
13 err_sys("signal error");
14
15 printf("%% ");
16
17 while( fgets(buf,MAXLINE,stdin) != NULL )
18 {
19 if( buf[strlen(buf) -1 ] == '\n' )
20 buf[strlen(buf) - 1] = 0;
21 if( (pid = fork()) < 0)
22 err_sys("fork() error");
23 else if(pid == 0)
24 {
25 execlp(buf,buf,(char *) 0);
26 err_ret("couldn't execute:%s",buf);
27 exit(127);
28 }
29
30 if ((pid = waitpid(pid,&status,0)) < 0)
31 err_sys("waitpid error");
32 printf("%% ") ;
33 }
34 printf("exit the while loop after receving the SIGINT signal\n");
35 exit(0);
36 }
37
38 void sig_int (int signo)
39 {
40 printf("interrupt\n%% ");
41 }
42
二、编译:
<bldc:/home/tingbinz/apue.2e/include/1>R*_*G:gcc -Wall -ggdb3 -o 1_8 1_8.c
In file included from apue.h:128,
from 1_8.c:1:
error.c: In function `err_doit':
error.c:106: warning: implicit declaration of function `vsnprintf'
error.c:108: warning: implicit declaration of function `snprintf'
三、运行结果:
<bldc:/home/tingbinz/apue.2e/include/1>R*_*G:./1_8
% date
Fri Sep 4 03:04:52 CDT 2015
% pwd
/home/tingbinz/apue.2e/include/1
% ^Cinterrupt
% exit the while loop after receving the SIGINT signal
<bldc:/home/tingbinz/apue.2e/include/1>R*_*G: