Re: [理工] 作业系统的process forking原理

楼主: HiltonCool (野兽疯)   2014-11-17 00:21:26
※ 引述《ifooleru (i服了u)》之铭言:
: Suppose that the process id of parent process and child process are 1999 and 2013 respectively. List the output generated at Line X, Y and Z.
: 父,子行程的process id 分别为1999 以及2013。请写出Line X, Y and Z 的输出。
: #include <sys/types.h>
: #include <stdio.h>
: #include <unistd.h>
: #define SIZE 5
: int nums[SIZE] = {0, 1, 2, 3, 4};
: int main()
: {
: int i;
: pid_t pid;
//create a new process
: pid = fork();
//child process
: if (pid == 0) {
: for (i = 0; i < SIZE; i++) {
: nums[i] *= -i;
: printf(" %d ", nums[i]); /* LINE X */
: }
//parent process
: }else if (pid > 0) {
: printf("My Process ID is %d \n", getpid()); /* LINE Y */
: wait(NULL);
: for (i = 0; i < SIZE; i++)
: printf(" %d ", nums[i]); /* LINE Z */
: }
: return 0;
: }
: 上面这个习题找不到讲义或有用的网页来了解原理
: 请问有人知道创造pid的forking该怎么一步步解释?
: 谢谢
首先main(parent process)先fork一个process(child process)
然后parent与child再各自执行自己的工作
虽然parent会等child工作结束后再执行for循环
但parent与child的nums阵列初始值皆为0,1,2,3,4
即使child更改了阵列内容也只会影响他自己的阵列内容而已
并不会影响到parent的阵列内容
所以parent与child会印出的内容如下:
child process => output:"0"
"-1"
"-4"
"-9"
"-16"
parent process => output:"My Process ID is 1999"
"0"
"1"
"2"
"3"
"4"
以上只是列出parent与child会印出的内容
整个程式执行结束后正确印出的内容如下:
"0" "My Process ID is 1999"
"-1" "0"
"-4" "-1"
"-9" "-4"
"-16" "-9"
"My Process ID is 1999" 或 "-16"
"0" "0"
"1" "1"
"2" "2"
"3" "3"
"4" "4"
虽然题目只是要求LINE X,Y,Z的值
但我把上述程式执行过程一并列出
可能会让你比较容易理解整个执行的过程
如有错误的地方再麻烦大家更正
作者: j897495 (咪咪)   2014-11-17 10:46:00
怎么知道父的num[i]值是多少 他没给条件耶@@
楼主: HiltonCool (野兽疯)   2014-11-17 11:29:00
初始值不是0,1,2,3,4吗?
作者: j897495 (咪咪)   2014-11-17 15:23:00
我漏看了 谢谢你详细教学:D

Links booklink

Contact Us: admin [ a t ] ucptt.com