目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
Estoy motivado para realizar cambios positivos en mi dieta después de leer esto Dieta
100 financing is a promising way for your investment.
I recently had the pleasure of using Emirates car recovery service, and I was impressed by their promptness, professionalism, and attention to detail car recovery dubai 24 hours
Car recovery in Dubai is made easy with car recovery al quoz . Trust their experienced team to handle any situation with efficiency and care for your vehicle
This was highly informative. Check out https://www.gamespot.com/profile/maryldevaw/ for more
Tolle Auswahl an Cannabis Samen auf deiner Seite! Werde definitiv etwas bestellen https://blogfreely.net/gertontxzj/cannabis-samen-bestellen-worauf-es-ankommt
바카라사이트추천에서는 추천 보너스를 받을 수 있는 사이트를 추천해드립니다 더 많은 것을 발견하십시오
Muszę przyznać, że jestem pod wrażeniem zawartości tej strony. Wszystko, czego potrzebowałem, znalazłem tutaj https://list.ly/otbertdtgb
This was highly educational. For more, visit Piedmont Triad Dumpsters
Thanks for the thorough analysis. Find more at Piedmont Triad Dumpsters
Vaše stránka je naprosto fantastická! Moc se mi líbí váš obsah o ##semena marihuany## cbd semena
Looking for affordable yet stable locksmith functions in Box Hill? Reach out to https://escatter11.fullerton.edu/nfs/show_user.php?userid=6621299 for unbeatable prices and prime-notch provider
바카라사이트추천에서는 추천하는 바카라 사이트를 소개해드립니다 더 많은 정보를 위해 클릭하십시오
¡Tu blog es justo lo que necesitaba! Estoy emocionado de explorar tus publicaciones y aprender todo sobre las semillas de marihuana semillas de marihuana
El papel de las compañías en la promoción de la salud es crucial. Informe SOFIA 2022
Thanks for the useful post. More like this at https://www.polygon.com/users/iortusdjoh
Muy buen artículo, proseguiré tus recomendaciones. salud
Las dietas basadas en plantas son el futuro Salud alimentaria
obviously like your web site however you need to take a look
at the spelling on several of your posts. Several of them are rife with spelling problems and I
find it very troublesome to tell the reality nevertheless I’ll
surely come back again.
I found this very interesting. Check out chatruletka18com for more
La pesca sostenible es fundamental para preservar las ciudades de peces Contaminación
I recently had the pleasure of using Emirates car recovery service, and I must say they exceeded my expectations in terms of professionalism and efficiency efficient car towing services in dubai
Thanks for the helpful advice. Discover more at cartiera
No real money needed: The cherry on top is the fact that demo accounts don’t need real-time money to work with.
##카지노사이트##에서 게임을 할 때 어떤 요소가 승패에 영향을 주는지 알려주세요 이 웹사이트를 엿보십시오
Thanks for the detailed post. Find more at https://milkyway.cs.rpi.edu/milkyway/show_user.php?userid=7399474
Integrar pescado en mi dieta ha mejorado notablemente mi salud Haga clic aquí
Świetne porady na temat sprzedaży mieszkania z najemcą! Na pewno skorzystam z Waszej strony, gdy będę potrzebował https://www.demilked.com/author/calenelukd/
Great insights! Discover more at Piedmont Triad Dumpsters
This was very beneficial. For more, visit 여기
I found this very helpful. For additional info, visit Piedmont Triad Dumpsters Greensboro NC
Deine Seite hat mir geholfen, die besten Cannabis Samen für meine medizinischen Bedürfnisse auszuwählen http://jasperrfps643.theglensecret.com/autoflowering-samen-indoor-pflege-und-ernte
The company also uses environmentally friendly packaging supplies, similar to glass and recycled paper. When it comes to purchasing Nature’s Sunshine products, you will want to ensure that you are sourcing them from respected and licensed distributors red clover
When it comes to car recovery services in Dubai, reliability and speed matter. That’s why you should choose car towing service dubai for all your needs
Díky vašemu webu jsem se naučil spoustu nových věcí o ##semena marihuany## https://folkd.com/blog/Feminizovan—sem–nka-marihuany–Jak-dos–hnout-vy——ho-v–nosu
I enjoyed this read. For more, visit https://www.demilked.com/author/rauterlyen/
Me encanta cómo abordas el tema de las semillas de marihuana en tu blog. Tus recomendaciones serán muy útiles para aquellos que desean iniciarse en el cultivo semillas autoflorecientes exterior
Need a reliable car recovery service provider in Dubai? Look no further than roadside assistance dubai , where customer satisfaction is our top priority, and your vehicle’s safety is our responsibility
This was quite enlightening. Check out https://hackerone.com/axminsdlga33 for more
Votre site est une véritable mine d’or pour tous les amateurs de graines de cannabis. Merci pour toutes les informations que vous partagez avec nous http://troyyvcq974.image-perth.org/comparatif-graines-feminisees-vs-regulieres
Marijuana has proven promise in cutting back irritation and dealing with discomfort associated with arthritis. Explore its prospective at semi cannabis
This blog provides a comprehensive guide to understanding the process of car recovery in Emirates, making it an essential resource for all drivers recovery vehicle near me
Say goodbye to outdated betting methods and hello to AI chatbots! Discover the innovative features of Shrt_cdK, and see how they have transformed the sports betting industry Gaming Innovations with AI
@Hannah Hale Article writing is also a fun, if you be familiar with then you can write if not it is complicated to write.
@Hannah Hale This is a very good tip especially to those fresh to the blogosphere.
Short but very precise information… Appreciate your sharing this one.
A must read article!
@Hannah Hale Pretty section of content. I just stumbled upon your site and in accession capital to assert
that I get in fact enjoyed account your blog posts.
Anyway I will be subscribing in your augment and even I success you get admission to constantly quickly.
@Hannah Hale I got this site from my buddy who informed me concerning this
website and at the moment this time I am visiting this
web site and reading very informative posts at this place.
My web-site: เครดิตฟรี กดรับเองไม่มีเงื่อนไข
@Hannah Hale Hi to every body, it’s my first go to see of this weblog; this blog includes amazing and actually
excellent data in favor of visitors.
Feel free to visit my homepage – สล็อตเว็บตรงไม่ผ่านเอเย่นต์ เครดิตฟรี
@Hannah Hale Very good blog you have here but I was wondering if you
knew of any message boards that cover the same
topics talked about here? I’d really like to be a part of online community where I can get responses from other experienced people that share the same interest.
If you have any recommendations, please let me
know. Thanks a lot!
@Hannah Hale I’d like to find out more? I’d want to find out more details.
Also visit my page – เว็บพนันออนไลน์ เว็บตรงไม่ผ่านเอเย่นต์ที่ดีที่สุด
@Hannah Hale If you wish for to obtain a good deal from this piece of writing then you
have to apply such strategies to your won weblog.
Feel free to surf to my website :: 1xbet
@Hannah Hale It is appropriate time to make a few plans for the future
and it is time to be happy. I’ve learn this publish and if I could I desire to
suggest you some fascinating issues or advice.
Maybe you could write next articles relating to this article.
I desire to read more issues about it!
my webpage เครดิตฟรี 200
@Hannah Hale I am in fact pleased to read this blog posts which includes plenty
of valuable information, thanks for providing these
kinds of data.
Here is my blog post … เครดิตฟรี88
@Hannah Hale Wow, this post is nice, my younger sister is analyzing these kinds of things, so I am going to tell her.
My site; 918kissเครดิตฟรี
@Hannah Hale https://avtoznak-dublikat.ru
@Hannah Hale Discovered an article that’s sure to appeal to you Р I recommend checking it out http://rt.rulet-18.com/
Me encanta que el atún sea tan bueno para la salud muscular Alimentación saludable
온라인바카라 추천 사이트로 유명한 이곳에서 다양한 바카라 게임을 즐길 수 있다는 것을 알게 되어 기뻐요! 더 많은 것을 여기에서 배우십시오
Fabulosa guía, ahora sé qué comer para sostenermeundefined artículo! Me ayudó a entender mejor de qué manera hacer mas fuerte mi sistema inmunológico https://www.cool-bookmarks.win/alimentos-que-no-pueden-faltar-en-tu-dieta-para-una-inmunidad-saludable
Es inspirador ver de qué forma la innovación puede llevarnos a una alimentación mucho más sostenible Innovación
저는 ##카지노사이트##에서 슬롯머신 게임을 즐기는 것이 가장 좋아요 여기로 이동하십시오
Increíble cómo la alimentación consciente puede editar nuestra salud y bienestar. sitio web
Super strona! Bardzo przydatne informacje dotyczące sprzedaży mieszkania z najemcą. Polecam wszystkim https://www.pexels.com/@richard-schut-1603324002/