1. We should pay attention that : Line 14 and 15 in 8_22.c was not reached whether the cmdstring is valid or invalid.
Because both of them will exit after the /bin/sh return.
2.For while (waitpid(pid,&status,0) < 0){. Why we should use while? Because It may retry when receive EINTR, we want to get the final exit status.
./personal_system
Wed Oct 28 00:27:30 CDT 2015
return value:0
normal termination,exit status = 0
sh: hddsjafdfds: not found
return value:256
normal termination,exit status = 1
/home/tingbinz/apue.3e/SBSCODE/8
return value:8448
normal termination,exit status = 33
:cat -n 8_22.c
1 #include "apue.h"
2 #include <errno.h>
3 #include <unistd.h>
4
5
6 int system(const char *cmdstring)
7 {
8 pid_t pid;
9 int status;
10 if ((pid = fork()) < 0){
11 status = -1;
12 }else if (pid == 0){
13 execl("/bin/sh","sh","-c",cmdstring, (char*) 0);
14 err_sys("execl:%s error",cmdstring);
15 _exit(127);
16 }else{
17 while (waitpid(pid,&status,0) < 0){
18 if (errno != EINTR){
19 status = -1;
20 break;
21 }
22 }
23 }
24 return (status);
25 }
cat -n 8_23.c
1 #include "apue.h"
2 #include "8_5.c"
3 #include "8_22.c"
4 #include <sys/wait.h>
5
6 int main()
7 {
8 int status;
9 if ((status = system("date")) < 0){
10 err_sys("system () error");
11 }
12 printf("return value:%d\n",status);
13 pr_exit(status);
14
15 if ((status = system("hddsjafdfds")) < 0)
16 err_sys("system () error");
17 printf("return value:%d\n",status);
18 pr_exit(status);
19
20 if ((status = system("pwd;exit 33")) < 0)
21 err_sys("system() error");
22 printf("return value:%d\n",status);
23 pr_exit(status);
24 return 0;
25 }
<bldc:/home/tingbinz/apue.3e/SBSCODE/8>R*_*G:cat -n 8_5.c
1 #include "apue.h"
2 #include <sys/wait.h>
3
4 void pr_exit(int status)
5 {
6 if( WIFEXITED(status) )
7 printf("normal termination,exit status = %d\n",WEXITSTATUS(status));
8 else if (WIFSIGNALED(status))
9 printf("abnormal termination, signal number = %d%s\n",WTERMSIG(status),
10 #ifdef WCOREDUMP
11 WCOREDUMP(status) ? " (core file generated)" : "");
12 #else
13 "");
14 #endif
15 else if (WIFSTOPPED(status))
16 printf("child stopped, signal number = %d\n", WSTOPSIG(status));
17 }