CSAPP 第三版 第八章 作业
自己做的 仅供参考 可能出现错误
注: 8.20 8.21 8.22 8.24 8.25 8.26 mark一下,这几题参考了学长的答案,在
https://www.cnblogs.com/liqiuhao/p/8107886.html
8.9
进程对 | 并发地? |
---|---|
AB | 否 |
AC | 是 |
AD | 是 |
BC | 是 |
BD | 是 |
CD | 是 |
8.10
A. fork
B. execve longjmp
C. setjmp
8.11
4
8.12
8
8.13
情况1.
x=2
x=4
x=3
情况2.
x=4
x=2
x=3
情况3.
x=4
x=3
x=2
8.14
3
8.15
5
8.16
counter = 2
8.17
情况1.
Hello
1
Bye
0
2
Bye
情况2.
Hello
0
1
Bye
2
Bye
情况3.
Hello
1
0
Bye
2
Bye
8.18
ACE
8.19
2^n
8.20
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
int main(int argc, const char *argv[], const char *envp[]) {
if (execve("/bin/ls", argv, envp))
perror("Failed to execve /bin/ls:\n");
return 0;
}
8.21
情况1.
abc
情况2.
bac
8.22
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int mysystem(char *command) {
pid_t sh_pid;
int sh_status;
if ((sh_pid = fork()) == 0)
execl("/bin/sh", "sh", "-c", command, (char *) 0);
else {
if ((waitpid(sh_pid, &sh_status, 0)) == sh_pid) {
if (WIFEXITED(sh_status))
return WEXITSTATUS(sh_status);
else if (WIFSIGNALED(sh_status)) {
fprintf(stderr, "command terminated by signal number %d.\n", WTERMSIG(sh_status));
if (WCOREDUMP(sh_status))
fprintf(stderr, "core dumped...\n", );
return WTERMSIG(sh_status);
}
else {
fprintf(stderr, "command terminated abnormally.\n");
fprintf(stderr, "return status information...\n");
return sh_status;
}
}
else {
fprintf(stderr, "Failed to reap /bin/sh.\n");
return EXIT_FAILURE;
}
}
}
8.23
信号不能用来对进程中发生的其他事情计数
8.24
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#define N 2
int main() {
int status;
pid_t pid;
for (int i = 0; i < N; i++) {
if (((pid = fork()) == 0)) {
int *p = 0;
*p = 0;
return 0;
}
}
while ((pid = wait(&status)) > 0) {
if (WIFEXITED(status))
printf("child %d terminated normally with exit status=%d\n", pid, WEXITSTATUS(status));
else if (WIFSIGNALED(status)) {
fprintf(stderr, "child %d terminated by signal %d", pid, WTERMSIG(status));
psignal(WTERMSIG(status), " ");
}
else
fprintf(stderr, "child %d terminated abnormally with status information=%d\n", pid, status);
}
if (errno != ECHILD)
fprintf(stderr, "waitpid error");
return 0;
}
8.25
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <setjmp.h>
#define TIMEOUT ((unsigned int)5)
#define SIZEOFBUF 1024
jmp_buf buf;
void SIGALRM_handler(int signum) {
longjmp(buf, 1);
}
char *tfgets(char *s, int size, FILE *stream) {
if (signal(SIGALRM, SIGALRM_handler) == SIG_ERR) {
perror("Failed to install SIGALRM_handler");
return NULL;
}
else
alarm(TIMEOUT);
if (!setjmp(buf))
return fgets(s, size, stream);
else
return NULL;
}
int main(int argc, const char *argv[]) {
char temp_bufer[SIZEOFBUF];
char *result = tfgets(temp_bufer, SIZEOFBUF, stdin);
if (result)
printf("Input : %s\n", result);
else
fprintf(stderr, "Time out!\n");
return 0;
}
8.26
是实验Shelllab就不写了