Today I work on the fork function to create child process.I find some interesting things . But maybe not for u . Because I am a little bird! The code :
//version 1.0
#include<sys/types.h> #include<stdio.h> #include<unistd.h> int main(){ pid_t pid,pid_1; printf("Starting ...\n"); //let's parent process prints 'a'
printf("a\n"); //let't creat the first child process ,it will print 'b'
pid = fork(); if(pid == 0){ printf("b\n"); } //let't create the second child process ,it will print 'c'
//Analyze: This is the very simple version.The parent process print "a" first. //Then it creates a child process and the child process print "b" . But after //creating the second child process ,it prints two "c". To sovle this ,we must //know the first point.When b process is created ,it continues running itself. //Ok,the instruction "pid_1=fork()" is executed by process b. So the first "c" is printed.While the parent process is also runnning, it will also executed "pid_1=fork()" ,so the second "c" is printed. We can sovle the two "c" problem //now. But I find another interesting result that the "Starting..." is only printed once.When child process is created , it inherits the parent's resource include the runtime state ,but the child process has it own data segment.Let's see Version 1.1 to show this.
//Version 1.1
#include<sys/types.h> #include<stdio.h> #include<unistd.h> int main(){ pid_t pid,pid_1; int i = 0; printf("Parent running...\n"); printf("Child process can't print this string.\n");
pid = fork(); if(pid == 0){ printf("Child process b prints: b\n");
i = 10 ;//Now I change its value from child process!
} if(pid>0){//return from parent process
i = 12;//Now I change its value from the parent process!
printf("a\n"); } //Let's print i value
printf("%d\n",i);//print 10 and 12 will prove my view that child proces
//has its own data segment.
pid_1 = fork();//two process will execute this!
if(pid_1 == 0){ printf("Child process c prints: c\n");
i = 11; printf("C process print i=%2d\n",i);//print 11
} if(pid_1>0){ printf("Well two parents print this\n"); } } //the output: //Parent running... //Child process can't print this string. //a //Child process b prints: b //12 //10 //Child process c prints: c //C process print i=11 //Child process c prints: c //C process print i=11 //Well two parents print this //Well two parents print this
//Analyze: //When parent creates a child process , the child proces will share the data //segment and code segment.But when we write to the parent or child , the child //process will create its own data segment or code segment.This is called COPYWRITE ?! But I can't sure!
NOTE: please give your advice for my discovery . Thank you!
NOTE: Thank you for your advice , I agree with you after I have saw some books,you are right.