OS-fork函数

本文探讨了 fork() 函数的工作原理,包括复刻鞋概念在进程创建中的应用。通过实例展示了父子进程间地址空间的独立性,并剖析了两个实验中PID变化的现象。焦点在于UNIX的地址空间复制机制和进程间的通信.
摘要由CSDN通过智能技术生成

实验一(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



*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值