深入理解计算机系统(第三版)家庭作业 第八章

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 2^n(每次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"; 

int main() 
{
    int status, i;
    pid_t pid;

    for (i = 0; i < N; i++)                       
		if ((pid = Fork()) == 0) { /* Child */     
			CONSTANT[0] = "A"; 		// 试图写只读常量
			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 暂略

  • 4
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值