OS:fork 函数-实验

实验一:fork原理

fork之前的代码是共同执行的

注意,子进程持有的是上述存储空间的“副本”,这意味着父子进程间不共享这些存储空间。
UNIX将复制父进程的地址空间内容给子进程,因此,子进程有了独立的地址空间。

#include <unistd.h>
#include <stdio.h>
#include<sys/types.h>
int main ()
{
    pid_t pid;
    int count=0;
    
	int i;
	pid=fork();
    if (pid < 0)
        printf("error in fork!");
    else if (pid == 0) {
        printf("child process, process id is %d\n",getpid());
        count++;   }
    else {
        printf("parent process, process id is %d\n",getpid());
		count++;     
	}
	printf("result: %d\n",count);
    return 0; 
	
}



//执行结果是:
/*
parent process, process id is 47085
result: 1
child process, process id is 47086
result: 1
*/




实验二:

fork(复刻)之后父进程的号不变,子进程的号+1

#include<stdlib.h> 
#include<stdio.h> 
#include<unistd.h> 
#include<sys/types.h> 
int main(){ 
	pid_t pid; 
	printf("the main_process_before_fork ID is %d\n",getpid()); 
	pid=fork(); 
	if(pid == 0 ){ 
		printf("the 子—process ID is %d\n",getpid()); 
		printf("hello,i am a child process. pid is %d\n",pid); 
	} else{ 
		printf("the 父-process ID is %d\n",getpid()); 
		printf("Hello,I'm a parent process.pid is %d\n",pid);
	} 
	exit(0); 
}

/*执行结果:


the main_process_before_fork ID is 48547
the 父-process ID is 48547
Hello,I'm a parent process.pid is 48548
the 子—process ID is 48548
hello,i am a child process. pid is 0



*/

posted @ 2020-12-05 19:29  leesoo  阅读(118)  评论(0)    收藏  举报