OSTEP:插叙:进程API
此系列主要完成操作系统导论(Operating Systems: Three Easy Pieces)的课后作业,还会涉及一些每章总结和感悟,大部分的题目都没有一个标准的答案,有争议和错误的地方欢迎同学们一起讨论。
相关资源
Website:http://www.ostep.org/
Homework:https://github.com/remzi-arpacidusseau/ostep-homework/
习题答案
本章习题需要编写C语言代码并运行,这里推荐使用GCC作为编译器,使用VIM作为编辑器。
1.子进程会有父进程的变量。两者同时修改互相不影响,因为每个进程有自己的内存空间。
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
int x = 100;
int rc = fork();
if (rc < 0) {
// fork failed; exit
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) {
x = 101;
printf("I am child process: %d\n", x);
} else {
x = 102;
printf("I am parent process: %d\n", x);
}
return 0;
}
2.两个进程都可以访问,并发写入时,会产生竞争,此时文件内容会因为操作系统的调度顺序不同而不同。注意 ,使用Wait系统调用可以让主进程等待子进程。
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
static void write_to_file(FILE *f, char *str) {
// APUE 8.9
char *ptr;
int c;
for (ptr = str; (c = *ptr++) != 0;) {
if (fputc(c, f) != c)
exit(1);
if (fflush(f) == EOF)
exit(1);
}
}
int main() {
FILE *f = fopen("./2.txt", "w+");
if (f == NULL)
exit(1