课本习题:
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