实验环境:ubuntu20.04
IDE:VScode
目录
只有纸质版的书,所以懒得打字了,使用的是作者提供的电子版PDF上的题目,应该也不难理解。
the first question
1. Write a program that calls fork(). Before calling fork(), have the main process access a variable (e.g., x) and set its value to something (e.g., 100). What value is the variable in the child process? What happens to the variable when both the child and parent change the value of x?
program:
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "sys/wait.h"
int main(int argc, char **argv){
int x = 100;
printf("main process(pid: %d)\n", (int)getpid());
printf("(main process) x: %d, address: %p\n", x, &x);
x = 10;
int rc = fork();
if(rc < 0){
fprintf(stderr, "fork failed");
exit(1);
}else if(rc == 0){
printf("child process(pid: %d)\n", (int)getpid());
printf("(child process) x: %d, address: %p\n", x, &x);
x = 50;
printf("(child process)changed x: %d\n", x);
}else{
//wait subprocess to finish
wait(NULL);
printf("(main process)changed x: %d\n", x);
}
return 0;
}
output
main process(pid: 21641)
(main process) x: 100, address: 0x7fffffffde60
child process(pid: 21658)
(child process) x: 10, address: 0x7fffffffde60
(child process)changed x: 50
(main process)changed x: 10
理解:
从上述结果中可以看出,子进程和主进程中x的地址是相同的,但是在子进程中修改x的值并不会影响主进程中x的值。
程序在分配内存中有两种方式:动态分配和提前分配。
显然这里x的内存已经提前申请了,所以在子进程和主进程中的x的地址必然是一样的,区别在于该地址是虚拟地址,子进程和主进程通过映射,将虚拟内存映射到不同的物理内存上,所以在子进程中修改主进程变量的值并不会作用的主进程变量的地址上。
通过fork创建子进程时,子进程会复制一块主进程的内存,但是拥有自己独立的内存空间。
the second question
2. Write a program that opens a file (with the open() system call) and then calls fork() to create a new process. Can both the child and parent access the file descriptor returned by open()? What happens when they are writing to the file concurrently, i.e., at the same time?
program:
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#include "sys/wait.h"
#include "fcntl.h"
int main(int argc, char **argv){
int i = 50;
close(STDOUT_FILENO);
open("./info.output", O_CREAT | O_WRONLY | O_TRUNC);
int rc = fork