8.9
进程对 | 并发地? |
---|---|
AB | 否 |
AC | 是 |
AD | 是 |
BC | 是 |
BD | 是 |
CD | 是 |
8.10 A、fork
B、longjmp,(execve调用成功时不返回)
C、setjmp
8.11 4(2个子进程,1个孙进程,1个父进程各打印一行)
8.12 8(同上,共4个进程,各打印2行)
8.13 432;243;423(三种可能性)
8.14 3次
8.15 5次
8.16 2(子进程和父进程不共享内存)
8.17 Hello 1 Bye 0 2 Bye
Hello 1 0 Bye 2 Bye
Hello 0 1 Bye 2 Bye
8.18 ACE
8.19 (每次fork都使原进程数翻倍)
8.20
#include "csapp.h"
int main(int argc, const char *argv[], const char *envp[])
{
if (execve("/bin/ls", argv, envp) < 0)
{
printf("/lib/ls not found.\n");
return -1;
}
return 0;
}
8.21 abc
bac
8.22 假设command不包含空格,如果包含,可调用parseline函数
#include "csapp.h"
int mysystem(char *command)
{
int status;
pid_t pid;
char *argv[4];
char *a0 = "sh";
char *a1 = "-c";
if( pid = Fork()==0 ) /*子进程*/
{
argv[0] = a0;
argv[1] = a1;
argv[2] = command;
argv[3] = NULL;
execve("/bin/sh", args, environ);
return -1; //执行异常
}
else{ /*父进程*/
if( waitpid(pid,&status,0) > 0)
{
if(WIFEXITED(status) != 0)
return WEXITSTATUS(status);
else return status;
}
else return -1; //wait异常
}
}
8.23 第一个信号发送给父进程后,父进程进入信号处理程序,并阻塞了SIGUSR2,此后第二个信号仍可以发送,但之后的信号都被丢弃,最终只有2个信号得到处理。
8.24
#include "csapp.h"
const char CONSTANT[4] = "FOO";
void modified_constant(char *p) {
p[0] = 'A';
}
int main()
{
int status, i;
pid_t pid;
for (i = 0; i < N; i++)
if ((pid = Fork()) == 0) { /* Child */
modified_constant(CONSTANT); // 试图写只读常量
exit(100 + i);
}
while ((pid = waitpid(-1, &status, 0)) > 0) {
if (WIFEXITED(status)) {
printf("child %d terminated normally with exit status=%d\n",
pid, WEXITSTATUS(status));
}
else if(WIFSIGNALED(status)) {
printf("child %d terminated by signal %d:", pid, WTERMSIG(status));
fflush(stdout);
psignal(WTERMSIG(status), NULL);
}
}
/* The only normal termination is if there are no more children */
if (errno != ECHILD)
unix_error("waitpid error");
exit(0);
}
8.25
#include "csapp.h"
#define TimeLimitSecs 5
sigjmp_buf env;
void tfgets_handler(int sig)
{
signal(SIGALRM, SIG_DFL);
siglongjmp(env, 1);
}
char *tfgets(char *buf, int bufsize, FILE *stream)
{
signal(SIGALRM, tfgets_handler)
alarm(TimeLimitSecs);
int rc = sigsetjmp(env, 1);
if(rc == 0)
return fgets(buf, bufsize, stream);
else
return NULL;
}
8.26 暂略