目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
카지노사이트에서의 최고의 선택, 웹사이트 링크 를 이용하시면 후회하지 않을 것입니다
Thanks for the useful post. More like this at dede4d
Appreciate the thorough write-up. Find more at Get more info
Karel MS2c Santral, işletmenizin ihtiyaçlarına tam olarak uyum sağlayacak özelleştirilebilir bir çözümdür. https://giphy.com/channel/mansizgunaydin7660 linkinizle daha fazla bilgi alabilirim
바카라사이트의 라이브 딜러와 함께 진행되는 게임을 즐겨보세요 더 많은 정보를 위한 클릭
바카라사이트의 라이브 딜러와 함께 진행되는 게임을 즐겨보세요 더 많은 정보를 얻기 위해 찾기
I would like to thank you for the efforts you have put in penning this website. I really hope to check out the same high-grade blog posts from you later on as well. In truth, your creative writing abilities has encouraged me to get my very own blog now 😉
슬롯사이트추천에서는 슬롯 사이트의 사용자 평가가 높은 사이트를 추천해드립니다 더 많은 것을 배우십시오
This excellent website definitely has all of the info I needed concerning this subject and didn’t know who to ask.
Capture Instagram-worthy shots of Dubai’s famous Atlantis, The Palm resort during an awe-inspiring helicopter tour helicopter tours dubai
This was quite informative. More at dede4d
Las cabañas en Pucón son perfectas para disfrutar de unas vacaciones en familia https://www.longisland.com/profile/cabanaspuconsloo/
Gracias por la recomendación de https://numberfields.asu.edu/NumberFields/show_user.php?userid=4061553 . Estoy buscando una inmobiliaria de confianza y definitivamente los consideraré
슬롯사이트추천으로 다양한 슬롯 사이트를 이용해보세요 정보를 위해 클릭하십시오
Karel MS2c Santral, işletmenizin iletişim altyapısını güçlendirmek ve verimliliği artırmak için ideal bir çözümdür. https://escatter11.fullerton.edu/nfs/show_user.php?userid=6653861 linkiniz için teşekkür ederim
After looking at a few of the articles on your website, I seriously like your way of writing a blog. I saved as a favorite it to my bookmark site list and will be checking back in the near future. Take a look at my web site as well and tell me what you think.
실력과 운을 시험할 수 있는 카지노사이트 추천, 더 많은 것을 발견하십시오 에서 함께 즐겨보세요
온라인바카라사이트추천은 다양한 게임을 제공하는 모바일 바카라 사이트를 찾는 것과 관련이 있습니다 여기에서 배우십시오
This was quite helpful. For more, visit dede4d
With havin so much content do you ever run into any problems of plagorism or copyright violation? My blog has a lot of completely unique
content I’ve either authored myself or outsourced but it
seems a lot of it is popping it up all over the internet without
my agreement. Do you know any methods to help prevent
content from being ripped off? I’d genuinely appreciate it.
Hot air ballooning in Dubai is an awe-inspiring experience that will make your heart race and leave you speechless https://nyc3.digitaloceanspaces.com/hotballoon/hotballoon/uncategorized/fly-substantial.html
카지노사이트 중에서도 최상의 선택 계속 읽기
Veoma korisne informacije! Nisam znao da se tablete za potenciju mogu kupiti bez recepta u apotekama. Za više detalja, obavezno posetite best prirodna rešenja za potenciju
Looking for a fun and unique way to explore Dubai? Rent a dune buggy from dune buggy dubai and get ready for an unforgettable desert adventure
Howdy! This article couldn’t be written much better! Going through this post reminds me of my previous roommate! He always kept talking about this. I am going to forward this information to him. Pretty sure he’ll have a good read. Thank you for sharing!
Get ready for an unforgettable experience as you soar above the stunning Dubai Desert Conservation Reserve on a helicopter tour book helicopter ride dubai
Gracias por compartir esta lista de inmobiliarias, especialmente por incluir a https://www.instapaper.com/read/1695925621
온라인슬롯에서 잭팟을 터뜨리세요! 웹사이트 링크
카지노사이트 추천 사이트입니다 더 많은 정보를 얻을 수 있습니다
This is a topic which is near to my heart… Take care! Exactly where can I find the contact details for questions?
Howdy very cool site!! Guy .. Excellent .. Wonderful .. I’ll
bookmark your website and take the feeds additionally?
I am happy to search out numerous useful information right
here in the put up, we need develop more strategies
in this regard, thanks for sharing. . . . . .
카지노사이트 추천으로 유명한 정보를 위해 클릭하십시오 에서 엄선된 게임을 즐겨보세요
Clearly presented. Discover more at ilumaplay
This was very enlightening. For more, visit https://www.openlearning.com/u/ednanash-sh0t3z/about/
Everyone loves it whenever people get together and share thoughts. Great website, stick with it!
The beauty of Dubai’s landscape is enhanced when you view it from a hot air balloon soaring high above hot air balloon dubai
Planning a desert safari in Dubai? Rent a dune buggy from Visit this website and make your adventure even more thrilling
I really love your website.. Very nice colors & theme. Did you build this amazing site yourself? Please reply back as I’m wanting to create my very own site and would like to learn where you got this from or just what the theme is called. Thanks.
바카라사이트에서 즐길 수 있는 다양한 게임 방법을 알려드립니다 추가 독서
##카지노사이트##에서 게임을 할 때 차단되거나 제한되는 사례가 있는지 알고 싶어요 이 링크 방문
Veoma korisne informacije! Nisam znao da se tablete za potenciju mogu kupiti bez recepta u apotekama. Za više detalja, obavezno posetite povećanje potencije prirodnim putem
Dubai’s skyline at sunset is pure magic, and a helicopter tour offers the best seat in the house to witness this breathtaking spectacle helicopter tour in dubai
Me siento más seguro al comprar una propiedad sabiendo que cuento con el apoyo de una inmobiliaria confiable como https://hackerone.com/eninmobiliariashgeh37
Thanks for the clear advice. More at https://maps.app.goo.gl/ZUMRHmoLtG99n53L8
슬롯사이트추천에서는 다양한 게임을 즐길 수 있는 옵션을 제공하는 사이트를 추천해드립니다 여기를 클릭하십시오
Thanks for the valuable article. More at ilumaplay
I blog frequently and I truly thank you for your content. Your article has truly peaked my interest. I’m going to take a note of your blog and keep checking for new information about once per week. I subscribed to your RSS feed too.
Thanks for the useful suggestions. Discover more at dede4d
I absolutely love your site.. Pleasant colors & theme. Did you build this web site yourself? Please reply back as I’m hoping to create my own website and would like to know where you got this from or just what the theme is called. Thank you.
최고의 카지노사이트 추천으로 이제는 더 이상 고민하지 마세요. 추가 정보 에서 당신의 선택을 기다립니다