我正在学习 xv6,我从 xv6 文档创建了一个如下所示的程序:
#include"types.h"
#include"user.h"
#include"param.h"
int main(){
int pid;
pid=fork();
if(pid > 0){
printf(0,"parent: child=%d\n", pid);
pid = wait();
printf(0,"child %d is done\n", pid);
}
else if(pid == 0){
printf(0,"child: exiting\n");
exit();
}
else {
printf(0,"fork error\n");
}
}
我使用
wait()
系统调用来确保两个进程的输出分开
但他们不是:
$ test
cphiarlde:n tex:iti ncg
hild=4
child 4 is done
pid 3 test: trap 14 err 5 on cpu 0 eip 0xffffffff addr 0xffffffff--kill proc
我应该怎么做才能解决这个问题?
正如评论中所建议的(@vhdl),您可以通过让孩子睡觉并等待父母写入控制台来引入一些基本的同步,因此:
diff --git a/user/ex_process_2.c b/user/ex_process.c
index f65cfb0..6e1ac50 100644
--- a/user/ex_process.c
+++ b/user/ex_process.c
@@ -11,6 +11,7 @@ main(int argc, char *argv[])
pid = wait((int *)0);
printf("child %d is done\n", pid);
} else if (pid == 0) {
+ sleep(1);
printf("child: exiting\n");
} else {
printf("fork error\n");
或者您可以在调用
wait
后让父打印,而不是尝试打印然后立即调用 wait
:
diff --git a/user/ex_process_2.c b/user/ex_process.c
index f65cfb0..22a8458 100644
--- a/user/ex_process.c
+++ b/user/ex_process.c
@@ -7,8 +7,8 @@ main(int argc, char *argv[])
int pid = fork();
if (pid > 0) {
- printf("parent: child=%d\n", pid);
pid = wait((int *)0);
+ printf("parent: child=%d\n", pid);
printf("child %d is done\n", pid);
} else if (pid == 0) {
printf("child: exiting\n");
目前就足够了,因为这只是开始,引入锁/互斥锁等同步概念还为时过早。
但是,这是一种获得并发性的好方法:)