目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
바카라사이트추천에서는 추천하는 바카라 사이트를 소개해드립니다 정보를 위해 클릭하십시오
이 카지노사이트 게임 사이트는 정말 신뢰할 수 있는 사이트로 알려져 있습니다 이 웹사이트를 보십시오
Looking for an adrenaline-fueled activity in Dubai? Rent a dune buggy from desert safari dubai booking and prepare yourself for an exciting off-road escapade
Gracias por la recomendación de https://cs.astronomy.com/members/eninmobiliariasecml/default.aspx . Estoy buscando una inmobiliaria de confianza y definitivamente los consideraré
Hi, I do think this is a great web site. I stumbledupon it 😉 I will revisit once again since I saved as a favorite it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.
Dubai helicopter tours provide an exclusive perspective of the city’s golden sands, crystal-clear waters, and vibrant urban landscape helicopter in dubai
Wonderful tips! Find more at https://www.indiegogo.com/individuals/37963069
Great job! Find more at ilumaplay
온라인바카라사이트 추천으로 다양한 바카라 게임을 즐겨보세요 여기에서 배우십시오
Zeytinburnu Karel Santral Servisi hizmetinizden memnun kaldım https://thegadgetflow.com/user/saygin0927/
Can I simply say what a comfort to uncover an individual who truly understands what they’re talking about over the internet. You certainly know how to bring an issue to light and make it important. More people really need to look at this and understand this side of the story. I was surprised that you’re not more popular because you most certainly have the gift.
I appreciated this post. Check out 더 읽기 for more
저는 ##카지노사이트##에서 게임을 즐기면서 동시에 보너스나 혜택도 받고 싶어요 이 포스트를 바로 여기에서 확인하십시오
Hvala vam na deljenju ovih informacija o tabletama za potenciju bez recepta! Za pronalaženje najboljih proizvoda, preporučujem posetu tabletezapotenciju.rs
Thanks for the great information. More at babish carbon steel wok review
Gracias por la recomendación de https://list.ly/lorenasovf . Estoy buscando una inmobiliaria de confianza y definitivamente los consideraré
Looking for an unforgettable adventure in Dubai? Rent a dune buggy with http://connernfde929.timeforchangecounselling.com/evening-desert-safari-dubai-witness-the-magic-of-a-desert-sunset and enjoy an adrenaline-fueled ride
This website was… how do I say it? Relevant!! Finally I’ve found something that helped me. Thanks a lot.
온라인바카라사이트에서는 추천하는 인기 있는 사이트를 이용해보세요 이 페이지 방문
Step into the shoes of a VIP as you embark on a luxurious helicopter tour in Dubai helicopter tours dubai
This was quite informative. For more, visit iluma play
This was quite informative. For more, visit dede4d
Aw, this was a very good post. Spending some time and actual effort to generate a great article… but what can I say… I hesitate a lot and never seem to get anything done.
These swimwear selections are fantastic for many who wish to sense self-confident and comfortable when swimming laps Bikinis With Vibrant Prints
Century 21, The Agency the best real estate in Mexico to find all the best offers for houses, apartments and land in Playa del Carmen, and other Playa del Carmen condo for sale
저는 ##카지노사이트##에서 다양한 게임을 즐기면서 동시에 보상도 받고 싶어요 여기서 더 많은 것을 발견하십시오
Muy interesante este artículo sobre las tendencias del mercado inmobiliario https://issuu.com/inmobiliariasyphb
If you’re tired of constantly readjusting your bikini, switch to a one piece swimsuit from Swim Shorts For Women and enjoy uninterrupted beach fun
For the best dune buggy rental service in Dubai, look no further than https://www.4shared.com/s/fNEQqyRrJfa . They offer top-quality vehicles and excellent customer support
A helicopter tour is not only a thrilling adventure but also an educational experience as you learn about Dubai’s rich history and culture from above helicopter sightseeing dubai
This was a great article. Check out https://www.demilked.com/author/thothegrhd/ for more
Imagine the feeling of being suspended in the sky, watching the sun rise over Dubai’s majestic skyline from a hot air balloon Click here to find out more
I enjoyed this article. Check out https://numberfields.asu.edu/NumberFields/show_user.php?userid=4036457 for more
This was very beneficial. For more, visit https://issuu.com/lynethraem
저희 더 많은 정보를 찾기 위해 찾기 에서는 다양한 게임과 특별한 혜택이 여러분을 기다리고 있습니다
An impressive share! I have just forwarded this onto a friend who had been conducting a little homework on this. And he in fact bought me dinner simply because I discovered it for him… lol. So allow me to reword this…. Thank YOU for the meal!! But yeah, thanks for spending time to discuss this subject here on your blog.
Remarkable! Its actually awesome post, I have got
much clear idea about from this piece of writing.
I could not resist commenting. Perfectly written.
카지노사이트 중에서도 최상의 선택 더 많은 정보를 얻기 위해 클릭하십시오
The best way to discover the hidden gems of Dubai’s deserts is by renting a dune buggy from morning desert safari dubai
Thanks for the detailed post. Find more at iluma play
This was quite informative. For more, visit dede4d
Phenq has actually made my weight management trip so much less complicated and much faster Craving management
I like it when individuals get together and share thoughts. Great blog, continue the good work.
Appreciate the thorough insights. For more, visit babish carbon steel wok review
This website definitely has all the information I needed concerning this subject and didn’t know who to ask.
Seeking an adrenaline-fueled escape in Dubai? Rent a dune buggy through best travel agency for dubai trips and enjoy the thrill of off-roading through the desert
Thanks for the insightful write-up. More like this at ilumaplay
This is quite enlightening. Check out iluma play for more
I used to be able to find good information from your content.