书本知识够你写出答案,但是如果你想验证你写的答案,就要一些额外的东西.这本书很多题目都是如此
/** mysystem.c*/
#include <stdio.h>
#include "csapp.h"int mysystem(char* command) {pid_t pid;int status;if ((pid = Fork()) == 0) {/*这里是关键用子程序去加载sh */char* argv[4] = { "", "-c", command, NULL };execve("/bin/sh", argv, environ);}/* print child pid so we can kill it */printf("child pid: %d\n", pid);if (Waitpid(pid, &status, 0) > 0) {/* exit normally */if (WIFEXITED(status))return WEXITSTATUS(status);/* exit by signal */if (WIFSIGNALED(status))return WTERMSIG(status);}
}int main(int argc, char* argv[]) {int code;code = mysystem("./exit-code");printf("normally exit, code: %d\n", code); fflush(stdout);code = mysystem("./wait-sig");printf("exit caused by signal, code: %d\n", code); fflush(stdout);return 0;
}
/** wait-sig.c*/
#include "csapp.h"int main(int argc, char* argv[]) {while (1);
}
/** exit-code.c*/
#include "csapp.h"int main(int argc, char* argv[]) {exit(10);
}