《深入理解计算机系统》第八章——异常控制流知识点总结

课本习题:

8.11

#include <unistd.h>
#include <stdio.h>

int main(){
    int i;
    for(i=0;i<2;i++) 
            fork();

    printf("hello\n");
    exit(0);

}

/*
 * Result:
 * hello
 * hello
 * hello
 * hello
 */

 8.12

#include <stdio.h>
#include <unistd.h>


void doit(){
    fork();
    fork();
    printf("hello\n");
    return;
}

int main(){
    doit();
    printf("hello\n");
    exit(0);
}

/*
 * Result:
 * hello
 * hello
 * hello
 * hello
 * hello
 * hello
 * hello
 * hello
 * /

8.13

#include <stdio.h>
#include <unistd.h>

int main(){
    int x = 3;

    if(fork() != 0)
            printf("x=%d\n",++x);

    printf("x=%d\n",--x);
    exit(0);
}

/*
 * Result:
 * x=4
 * x=3
 * x=2
 *
 */

8.14

#include <stdio.h>
#include <unistd.h>


void doit(){
    if(fork() == 0){
        fork();
        printf("hello\n");
        exit(0);
    }

    return;
}

int main(){
    doit();
    printf("hello\n");
    exit(0);
}

/*
 * Result:
 * hello
 * hello
 * hello
 */

8.15

#include <stdio.h>
#include <unistd.h>

void doit(){
    if(fork()==0){
        fork();
        printf("hello\n");
        return;
    }
    return;
}

int main(){
    doit();
    printf("hello\n");
    exit(0);
}

/**
 * Result
 * hello
 * hello
 * hello
 * hello
 * hello
 */


8.16

#include <stdio.h>
#include <unistd.h>

int counter = 1;

int main(){
    if(fork()==0){
        counter++;
        exit(0);
    } else {
        wait(NULL);
        printf("couter = %d\n",++counter);
    }
    exit(0);
}

/**
 * Result:
 * counter = 2
 */

8.21

#include <stdio.h>
#include <unistd.h>


int main(){
    if(fork()==0){
        printf("a");
        fflush(stdout);
        exit(0);
    } else {
        printf("b");
        waitpid(-1,NULL,0);
    }

    printf("c");
    fflush(stdout);
    exit(0);
}

/**
 * Result:
 * abc
 */

 

 p518

#include <stdio.h>
#include <unistd.h>


int main(){
    if(fork()==0){
        printf("a");
        fflush(stdout);
        
    } else {
        printf("b");
        waitpid(-1,NULL,0);
    }

    printf("c");
    fflush(stdout);
    exit(0);
}

 8.19下面的函数会打印出多少行输出?用一个N的函数给出答案,N>=1.

#include <stdio.h>
#include <unistd.h>

void foo(int n){
    int i;
    for(i=0;i<n;i++)
        fork();
    printf("hello\n");
    exit(0);
}

int main(){
    foo(4);
    return 0;
}

Answer:2^N

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值