目录
问题
- 有的时候,程序运行后的输出结果会在cmd的输出提示之后:
- 本实验中是父进程创建了两个子进程,然后父进程输出 a 后结束,子进程分别输出 b c 后结束。
- 出现该问题其实就在于父进程可能比子进程先结束,此时cmd提示就会冒出来。
- 当我们在命令行里面输入命令并回车执行时,命令内容是交给了shell去执行,而shell是有很多种具体实现的程序:如 bath,zsh ...... 并且正在使用的 shell 是可以修改的。
- 需要查看自己的shell是谁,可以执行cmd命令:echo $SHELL
- cmd就会输出当前使用的shell的位置:
- 原因:我们在shell中运行我们写的实验程序($ ./fork_main)时,shell会等待fork_main这个进程结束,但fork_main里面又创建了两个子进程,shell是不管的,一旦shell启动的父进程fork_main结束,shell的提示(coolight@coolight-Desktop:~$)就会冒出来,而此时子进程才开始输出,因此会出现有些程序输出是在shell提示之后。
实验具体内容
实验内容
编写一段程序,使用系统调用fork( )创建两个子进程。当此程序运行时,在系统中有一个父进程和两个子进程活动。让每一个进程在屏幕上显示一个字符:父进程显示'a',子进程分别显示字符'b'和字符'c'。试观察记录屏幕上的显示结果,并分析原因。
涉及的系统调用
- fork()
- 创建一个新进程。
- 系统调用格式:
- pid=fork( )
- 参数定义:
- int fork( )
- fork( )返回值意义如下:
- 0:在子进程中,pid变量保存的fork( )返回值为0,表示当前进程是子进程。
- >0:在父进程中,pid变量保存的fork( )返回值为子进程的id值(进程唯一标识符)。
- -1:创建失败。
- 如果fork( )调用成功,它向父进程返回子进程的PID,并向子进程返回0,即fork( )被调用了一次,但返回了两次。此时OS在内存中建立一个新进程,所建的新进程是调用fork( )父进程(parent process)的副本,称为子进程(child process)。子进程继承了父进程的许多特性,并具有与父进程完全相同的用户级上下文。父进程与子进程并发执行。
- 核心为fork( )完成以下操作:
- (1)为新进程分配一进程表项和进程标识符,进入fork( )后,核心检查系统是否有足够的资源来建立一个新进程。若资源不足,则fork( )系统调用失败;否则,核心为新进程分配一进程表项和唯一的进程标识符。
- (2)检查同时运行的进程数目,超过预先规定的最大数目时,fork( )系统调用失败。
- (3)拷贝进程表项中的数据,将父进程的当前目录和所有已打开的数据拷贝到子进程表项中,并置进程的状态为“创建”状态。
- (4)子进程继承父进程的所有文件,对父进程当前目录和所有已打开的文件表项中的引用计数加1。
- (5)为子进程创建进程上、下文,进程创建结束,设子进程状态为“内存中就绪”并返回子进程的标识符。
- (6)子进程执行,虽然父进程与子进程程序完全相同,但每个进程都有自己的程序计数器PC(注意子进程的PC开始位置),然后根据pid变量保存的fork( )返回值的不同,执行了不同的分支语句。
- 例:
….. pid=fork( ); if (! pid) printf("I'm the child process!\n"); else if (pid>0) printf("I'm the parent process! \n"); else printf("Fork fail!\n"); …… |
….. pid=fork( ); if (! pid) printf("I'm the child process!\n"); else if (pid>0) printf("I'm the parent process!\n "); else printf("Fork fail!\n"); …… | ….. pid=fork( ); if (! pid) printf("I'm the child process!\n"); else if (pid>0) printf("I'm the parent process!\n "); else printf("Fork fail!\n"); …… |
源代码
#include <iostream>
#include <unistd.h>
using namespace std;
int main()
{
cout << "<< coolight | [软件202,2006300052,郑泳坤]" << endl;
int fork_num = fork();
if(fork_num == -1){
cout << "<< fork Error" << endl;
}else if(fork_num == 0){ //子进程
fork_num = fork();
if(fork_num == -1){
cout << "<< fork Error" << endl;
}else if(fork_num == 0){ //子进程
sleep(0.5);
cout << "c" << endl;
}else if(fork_num > 0){
sleep(0.5);
cout << "b" << endl;
}
}else if(fork_num > 0){
sleep(0.5);
cout << "a" << endl;
}
return 0;g
}
运行结果截图
思考
- 系统是怎样创建进程的?
- 主要是四个步骤
- 申请空白PCB(过程控制块)
- 为新工序分配资源
- 初始化PCB
- 将新进程插入就绪队列
- 当使用fork()创建时将复制父进程的PCB块,U区和内存图像到新进程。Fork()会用到写时复制,子进程会和父进程共享一些资源,直到有人对一部分数据进行写操作,才会真正开辟空间复制出来这一部分资源
- 主要是四个步骤
- 当首次调用新创建进程时,其入口在哪里?
- 父进程和子进程入口都在fork()函数调用的下一句指令代码。但由于fork()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
다양한 바카라 게임을 실시간으로 즐길 수 있는 온라인바카라사이트입니다 더 많은 것을 발견하십시오
Car recovery Dubai’s team of experts is equipped with the necessary skills and knowledge to handle any type of vehicle breakdown effectively recovery vehicle jebel ali
This was quite useful. For more, visit chatruletka18com
I’ve been recommending recovery vehicle in dip dubai to all my friends and family in the Emirates. Their car recovery services are truly exceptional
I liked this article. For additional info, visit Big Boom Agency Greensboro NC
카지노사이트 추천으로 인정받는 더 많은 정보를 찾기 위해 클릭하십시오 에서 다양한 게임 옵션을 만나보세요
몸캠피싱에 대해 알림 받아보니 정말 경계해야 할 일인 것 같아요. 저희 여기 에서는 이와 관련된 유용한 정보를 제공하고 있어요
동영상유포 피해 문제는 점점 심각해지고 있는데, 이에 대한 대응이 미비한 것 같아요. 더 많은 도움말 을(를) 통해 이러한 문제에 대한 노력을 알아볼 수 있겠네요
Thanks for the thorough article. Find more at 더 많은 정보를 얻기 위해 찾기
다양한 게임 옵션을 제공하는 슬롯사이트를 추천합니다 추가 독서
Flurex Sports understands the needs of athletes and ensures their sports clothing is designed to optimize performance wholesale workout clothes Flurex Sports
언제 어디서나 즐길 수 있는 최고의 카지노사이트 추천, 이 사이트를 살펴보십시오 에서 다양한 게임을 즐겨보세요
Need assistance with car recovery in Dubai? Look no further than Learn more here – they have the expertise and equipment to handle any situation
동영상유포 피해에 대한 정보를 얻을 수 있는 곳이 없어서 답답한 마음이 들었는데, 계속 읽기 을(를) 통해 해결책을 찾을 수 있을 것 같아요
몸캠피싱은 정말 미묘한 수법으로 사람들을 속이는군요. 저희 더 많은 정보를 얻기 위해 찾기 에서는 이와 관련된 유용한 정보를 제공하고 있습니다
Thanks for sharing this valuable information! https://raindrop.io/balethszwj/bookmarks-46395006 is now on my list of trusted car recovery services when driving in the Emirates
Aw, this became an exceptionally nice post. In thought I have to place in writing like this additionally – spending time and actual effort to make a good article… but exactly what can I say… I procrastinate alot and by no means often go carried out.
온라인카지노사이트 추천을 위해 사용자 리뷰를 확인하면서 신뢰할 수 있는 사이트를 선택할 수 있습니다 이 사이트를 둘러보기
바카라 전략을 활용하여 게임에 참여해보세요 더 많은 정보를 찾기 위해 찾기
Thanks for the comprehensive read. Find more at maco4d
Razem te trzy składniki pomagają organizmowi wspierać zdrowe połączenie umysł-ciało. Nigdy nie zarobił złotówki, poprawka, zarobił grosze przez pół roku które wydał na ich specyfiki kliknij tutaj
Looking for reliable sports clothing that can withst fitness wear wholesale Flurex Sports
Awesome things here. I’m very glad to peer your post.
Thanks so much and I am having a look ahead to contact you.
Will you kindly drop me a mail?
Appreciate the comprehensive insights. For more, visit 더 많은 유용한 힌트
영상유포 피해로부터 안전하게 지키는 방법과 관련된 정보입니다 추가 독서
바카라사이트추천에서는 다양한 게임 옵션을 제공하는 사이트를 추천해드립니다 더 많은 정보를 찾기 위해 찾기
동영상유포 피해로 인한 정신적 고통은 상상하기만 해도 가슴 아픕니다. 여기를 클릭하십시오 을(를) 통해 이런 고통을 줄일 수 있는 방법을 찾고 싶어요
Appreciate the thorough information. For more, visit Big Boom Agency Greensboro
Car breakdowns can happen when you least expect them. Stay prepared by saving the contact details of Fulldown recovery dubai , Dubai’s trusted car recovery service provider
Thanks for sharing this informative blog post! Fulldown recovery dubai is now on my list of trusted car recovery services whenever I’m driving in the Emirates
##카지노사이트##에서는 어떤 게임을 하면 보다 많은 보너스 혜택을 받을 수 있는지 궁금해요 여기를 클릭하십시오!
Generally I don’t learn post on blogs, however I would like to say that this write-up very
forced me to check out and do it! Your writing taste has been amazed
me. Thanks, quite nice post.
Great insights! Discover more at 좋은 사이트
Stay motivated and inspired with Flurex Sports’ sports clothing that reflects your passion for fitness sportswear clothing manufacturer Flurex Sports
영상유포 피해를 예방하기 위한 실용적인 방법을 도움이 되는 자원 에서 배워보세요
다양한 바카라 게임을 실시간으로 즐길 수 있는 온라인바카라사이트입니다 더 많은 도움말
온라인카지노사이트 추천을 위해 사용자 리뷰를 확인하면서 신뢰할 수 있는 사이트를 선택할 수 있습니다 더 읽기
영상유포 피해 예방을 위한 유용한 자료를 더 많은 정보를 찾기 위해 클릭하십시오 에서 찾아보세요
This was nicely structured. Discover more at Big Boom Agency
When it comes to car recovery services in Dubai, reliability and speed matter. That’s why you should choose https://milkyway.cs.rpi.edu/milkyway/show_user.php?userid=7373091 for all your needs
This was a great help. Check out 여기를 클릭하십시오 for more
This blog has everything one needs to know about Emirates car recovery services. The step-by-step guide and useful tips make it a must-read for all motorists recovery vehicle dubai
Stay comfortable and stylish during your workouts with Flurex Sports’ range of sports clothing fitness clothing suppliers Flurex Sports
동영상유포 피해로부터의 보호를 위해서는 법적인 지원도 필요합니다. 이 포스트를 바로 여기에서 확인하십시오 을(를) 통해 이런 법적인 지원을 받을 수 있는 방법을 알려주세요
This was a fantastic resource. Check out 이 웹사이트 방문 for more
몸캠피싱에 대해 잘 알려주셔서 감사합니다. 저희 여기 에서도 이와 관련된 다양한 정보를 제공하고 있어요
온라인슬롯사이트에서는 인기 있는 슬롯 사이트를 추천해드립니다 여기를 확인하십시오
Aw, this was an extremely nice post. Spending some time and actual effort to make a good article… but what can I say… I put things off a lot and don’t seem to get nearly anything done.
Great job! Discover more at Big Boom Agency
동영상유포 피해 문제에 대한 정보를 얻을 수 있는 곳이 없어서 답답한 마음이 들었는데, 이 포스트를 바로 여기에서 확인하십시오 을(를) 통해 해결책을 찾을 수 있을 것 같아요