1.8 从标准输入读命令并执行2
proc/shell2.c
1 #include "apue.h" 2 #include <sys/wait.h> 3 static void sig_int(int); /* our signal-catching function */ 4 int 5 main(void) 6 { 7 char buf[MAXLINE]; /* from apue.h */ 8 pid_t pid; 9 int status; 10 if (signal(SIGINT, sig_int) == SIG_ERR) 11 err_sys("signal error"); 12 printf("%% "); /* print prompt (printf requires %% to print %) */ 13 while (fgets(buf, MAXLINE, stdin) != NULL) { 14 if (buf[strlen(buf) - 1] == '\n') 15 buf[strlen(buf) - 1] = 0; /* replace newline with null */ 16 if ((pid = fork()) < 0) { 17 err_sys("fork error"); 18 } else if (pid == 0) { /* child */ 19 execlp(buf, buf, (char *)0); 20 err_ret("couldn't execute: %s", buf); 21 exit(127); 22 } 23 /* parent */ 24 if ((pid = waitpid(pid, &status, 0)) < 0) 25 err_sys("waitpid error"); 26 printf("%% "); 27 } 28 exit(0); 29 } 30 void 31 sig_int(int signo) 32 { 33 printf("interrupt\n%% "); 34 }优质内容筛选与推荐>>