目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
Fantastic post! Discover more at https://www.anobii.com/en/01868ee5bcbad0a3ba/profile/activity
몸캠피싱 피해를 예방하기 위해 저희 더 많은 정보를 위한 클릭 에서는 다양한 대처 방법을 안내하고 있습니다
When I was walking through the manufacturing plant today,
the gleaming areas of stainless steel captivated my attention at every turn.
It’s fascinating to see how this alloy, made up mainly of iron, chromium, and nickel, has grown into an integral element
of our modern-day world. From the massive vats within the food processing sector to the intricate medical instruments used in cleanrooms, stainless steel’s versatility never ceases
to amaze me.
Good post. I learn something totally new and challenging on sites I stumbleupon on a daily basis. It’s always useful to read through content from other authors and use a little something from other web sites.
Hot air ballooning in Dubai is a unique way to escape the hustle and bustle of the city and enjoy serene moments in the sky balloon adventures dubai
동영상유포 피해로 인한 정신적 고통은 상상하기만 해도 가슴 아픕니다. 여기서 더 많은 것을 발견하십시오 을(를) 통해 이런 고통을 줄일 수 있는 방법을 찾고 싶어요
Helpful suggestions! For more, visit https://www.anobii.com/en/01d6909e58d67864d1/profile/activity
Thanks for the detailed post. Find more at Have a peek here
La inteligencia artificial transformará los entrenamientos. Haga clic aquí
Thanks for the great explanation. Find more at random video chat
Howdy! This blog post couldn’t be written much better! Looking at this post reminds me of my previous roommate! He always kept preaching about this. I’ll forward this post to him. Pretty sure he’s going to have a great read. Many thanks for sharing!
I recently availed Emarates Car Recovery’s services, and I was impressed with their prompt response and efficient assistance. Their team ensured a hassle-free experience from start to finish Hop over to this website
Traveling with a group? Renting a spacious and snug car or truck from Rideshare Perth will will let you savour your journey mutually even as exploring the wonders of Perth
Thanks for the clear breakdown. Find more at cctv batam
I could not refrain from commenting. Exceptionally well written!
동영상유포 피해로 인한 정신적 고통은 상상하기만 해도 가슴 아픕니다. 좋은 사이트 을(를) 통해 이런 고통을 줄일 수 있는 방법을 찾고 싶어요
Need urgent car recovery assistance in Dubai? recovery vehicle near me is just a phone call away, ready to provide reliable and professional services whenever you need them, offering peace of mind during stressful situations
If you value convenience and adaptableness at the same time as travelling, I awfully counsel renting a car or truck from Rent A Car Perth in Perth. You shouldn’t feel sorry about having the freedom to discover at your recreational
Gracias por la información descriptiva sobre cómo funcionan los fondos de inversión Comercializadora de luz y gas
몸캠피싱은 정말 심각한 문제인 것 같아요. 저희 더 많은 정보를 찾아보십시오 에서는 이와 관련된 최신 정보와 대처 방법을 안내해드리고 있습니다
Learn here stands out for their commitment to sustainability in maritime shipping, reducing carbon emissions and promoting eco-friendly practices
Quality content is the main to be a focus for the viewers to pay a visit the site, that’s what this site is providing.
This was a wonderful guide. Check out https://www.anime-planet.com/users/lavellmxjd for more
If you’re seeking to upgrade your pickleball paddle, bear in mind to trust making an investment in a advantageous overgrip from pickleball paddle grips for sale . It’s a small investment which will make a marvelous effect on your efficiency
Don’t enable transportation barriers restrict your exploration of Perth’s outstanding attractions. Renting a vehicle from https://www.longisland.com/profile/abbotsxwlm/ ensures that you can actually event the entirety this city has to offer
Additional reading ‘s cutting-edge technology and innovative solutions make them a leader in the maritime shipping industry
Dubai offers endless opportunities for amazing experiences, and hot air ballooning is definitely one of them hot air balloon ride dubai
Conciso y práctico Plantas fotovoltaicas
Need a nontoxic mode of transportation in the course of your continue to be in Perth? Choose Long Term Car Hire Perth for his or her %%!%%baa874c1-third-463f-80bb-48880b67ddc4%%!%% vehicle rental features, permitting you to navigate the town easily
몸캠피싱에 대해 깊게 알아보니 실제로 많은 사람들이 피해를 입는군요. 저희 여기로 엿보기 에서 제공하는 안전한 사용 팁을 참고하세요
Trusting https://www.scoop.it/u/isaac-cresci with my maritime shipping needs was a decision I will never regret
영상유포 피해로부터 안전하게 보호되는 방법과 관련된 정보입니다 더 많은 정보를 얻을 수 있습니다
Quad biking in Dubai is an absolute must-do! Rent yours from quad biking dubai and immerse yourself in the beauty of the desert
Whether you are vacationing Perth for a day or a month, renting a car from Perth Car Rental will offer you the freedom to customize your itinerary and make the maximum out of your time out
I found this very interesting. For more, visit free video chat
Appreciate the thorough write-up. Find more at penangkal petir batam
Excelente punto sobre la relevancia de la gestión financiera https://www.instapaper.com/read/1696623146
This was a great help. Check out https://numberfields.asu.edu/NumberFields/show_user.php?userid=4065789 for more
Don’t permit transportation troubles preclude your journey trip in Perth. Renting a auto from https://www.anobii.com/en/01703c3761e72c55ea/profile/activity ensures a delicate and snug trip throughout the time of your dwell
Fondos prometedores con estrategias adecuadas. Sector fotovoltaico español
There’s something truly magical about floating through the sky in a hot air balloon hot air balloon dubai
Renting a automotive from https://www.cheaperseeker.com/u/ceinnadqqw was once the superb determination I made at some stage in my shuttle to Perth. It allowed me to seek advice from all of the attractions alone time table and at my own speed
If you might be critical approximately improving your pickleball recreation, do not overlook the magnitude of a exquisite overgrip. I’ve been by using can you use tennis overgrip on pickleball paddle ‘s overgrips, and they’ve greatly superior my management and accuracy
Thanks for the great tips. Discover more at free video chat
Howdy, I think your blog could be having internet browser compatibility issues. When I look at your site in Safari, it looks fine however, when opening in IE, it has some overlapping issues. I merely wanted to give you a quick heads up! Apart from that, excellent site!
I must thank you for the efforts you have put in writing this blog. I’m hoping to see the same high-grade blog posts from you in the future as well. In truth, your creative writing abilities has inspired me to get my own, personal website now 😉
El artículo ha sido muy útil para entender mejor las oportunidades en estos mercados consultar aquí
몸캠피싱 피해를 예방하기 위해 꼭 알아야 할 정보들을 저희 여기를 클릭하여 정보를 얻으십시오 에서 확인하실 수 있어요
Evaluación precisa de las estrategias. Ganancias
Hiring a auto from Short Term Car Rental Perth in Perth isn’t very almost getting from element A to point B; this is about embracing the pleasure of using and having an unforgettable journey