目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
I’m really loving the theme/design of your blog. Do you ever run into any web browser compatibility problems? A few of my blog audience have complained about my site not operating correctly in Explorer but looks great in Opera. Do you have any recommendations to help fix this issue?
This one is an inspiration personally to uncover out far more associated to this subject. I need to confess your knowledge prolonged my sentiments as well as I’m going to proper now take your feed to remain updated on each coming blog posts you would possibly presumably create. You are worthy of thanks for a job perfectly performed!
hello there and thank you for your info – I have certainly picked up something new from right here. I did however expertise several technical issues using this site, as I experienced to reload the web site lots of times previous to I could get it to load properly. I had been wondering if your web hosting is OK? Not that I’m complaining, but sluggish loading instances times will very frequently affect your placement in google and could damage your quality score if advertising and marketing with Adwords. Well I am adding this RSS to my e-mail and can look out for much more of your respective exciting content. Make sure you update this again soon..
Hi. best wishes to you and your very nice blog”
Thanks for this post. I definitely agree with what you are saying. I have been talking about this subject a lot lately with my mother so hopefully this will get him to see my point of view. Fingers crossed!
I always visit new blog everyday and i found your blog.`~–*
i like chaning tatum because he has a great body, just look at those chest muscles*
Easily, the post is really the greatest on this laudable topic. I concur with your conclusions and will thirstily look forward to your future updates. Saying cheers will not just be sufficient, for the brilliant c lucidity in your writing. I will instantly grab your rss feed to stay privy of any updates. Solid work and much success in your business enterprise!
I always visit new blog everyday and i found your blog.,,-:*
Thank you pertaining to discussing that superb content material on your web site. I ran into it on the search engines. I am going to check to come back after you publish extra aricles.
At times your website will be loading gradually, better find a far better web host.
Hi my family member! I want to say that this article is amazing, great written and include approximately all vital infos. I’d like to look extra posts like this.
This web-site can be a walk-through rather than the information you wished about it and didn’t know who must. Glimpse here, and you’ll definitely discover it.
howdy, I am gettin my site ranked “lands end catalog”.
I definitely wanted to jot down a note to be able to express gratitude to you for all of the wonderful tactics you are giving on this site. My time-consuming internet search has now been paid with incredibly good ideas to exchange with my best friends. I ‘d suppose that we visitors are very much blessed to be in a remarkable network with so many outstanding people with insightful opinions. I feel rather blessed to have used the web pages and look forward to many more fun times reading here. Thank you again for everything.
nice post! am looking forward to read your future post, great weekend ahead!
Hello! I would wish to make a enormous thumbs up to the fantastic information you may have here within this post. I will be returning to your blog for more soon.
There are various agencies which deals with evidences located at a crime scene. Police use it for investigation, prosecuting attorney presents it before court of law as well as a forensic science technician analyzes evidences thoroughly to help other agencies in criminal procedure. A forensic science technician conducts comprehensive chemical and physical study of evidence submitted by a law enforcement agency
learning toys can enable your kids to develop their motor skills quite easily;;
It is truly a nice and helpful piece of information. I’m satisfied that you just shared this helpful tidbit with us. Please stay us up to date like this. Thank you for sharing.
healthy eating should be our top priority since there are many junk foods and foods with no nutritional value these days..
Spot on with this write-up, I actually believe this site requirements additional consideration. I’ll more likely once more to study additional, many thanks for that information.
Most what i read online is trash and copy paste but i think you offer something different. Keep it like this.
It’s difficult to acquire knowledgeable folks during this topic, nevertheless, you be understood as do you know what you’re referring to! Thanks
I think one of your advertisements triggered my internet browser to resize, you might want to put that on your blacklist.
Respect to post author, some fantastic information .
There is noticeably a lot of money to learn about this. I suppose you made particular nice points in features also.
After a brief firefight that results in the hood of Highsmith’s car getting blown into the windshield, the two inadvertently crash into the side of a double decker bus.
I dugg some of you post as I thought they were extremely helpful handy
This is actually a good influencing view on this particular idea. And I’d like you to know that I’m really glad you shared your thoughts plus knowledge and I find that i agree. I truly truly appreciate the straightforward writing along with the focus you have invested writing this posting. Loads of thanks yous for that good work plus very good luck with the website, I most certainly will be awaiting new topics within the future.
Loving the info on this internet site , you have done outstanding job on the articles .
Great post , I am going to spend more time researching this topic
I’m impressed, I have to admit. Truly rarely do I encounter a blog that’s both educative and entertaining, and without a doubt, you’ve hit the nail on the head. Your notion is outstanding; the pain is an element that not enough folks are speaking intelligently about. My business is happy that I stumbled across this in my search for something regarding this.
Augustine thanks for sharing this! My extensive google search has now been recently paid for using quality insight to talk about together with our relatives.
Today, considering the fast chosen lifestyle that everyone is having, credit cards have a huge demand in the economy. Persons throughout every discipline
You made some decent points there. I looked on the net to the issue and located most individuals is going coupled with with all your internet site.
Have you ever considered writing an ebook or guest authoring on other websites? I have a blog centered on the same subjects you discuss and would love to have you share some stories/information. I know my readers would value your work. If you’re even remotely interested, feel free to send me an email.
Hi there, just became alert to your blog through Google, and found that it’s really informative. I am going to watch out for brussels. I will appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!
[…]although websites we backlink to below are considerably not related to ours, we feel they are actually worth a go through, so have a look[…]…
cheers for such a brilliant site. Where else could someone get that kind of info written in such a perfect way? I have a presentation that I am presently working on, and I have been on the watch out for such information.
If you are one of those, who possess the ardent desire of making a home bar, then the bar woodworking plans will proficiently guide you to fulfill this objective.
Youre so cool! I dont suppose Ive read anything this way prior to. So nice to seek out somebody by incorporating original thoughts on this subject. realy we appreciate you beginning this up. this fabulous website is one thing that is needed over the internet, someone after a little originality. useful problem for bringing something new towards the net!
Fantastic write-up, many thanks. I just agreed to your rss feed!
How do I start to learn how to Hip Hop dance?
Decidedly refreshing idea, I suppose I will give it a shot. Thanks!
An array of wild hair caution equipment in hair apply, tweezers, hydrogen stick reviews frizzy hair scissors, frizzy hair sawing scissors, sheers, specialist sheers, frizzy hair sheers, frizzy hair hair comb, bobby pin, head piece, eyelash curler, hair hair brush, plus shower limitation accessories can be purchased.
I feel there’s a problem with your web site using Firefox browser.
Hey this can be a great looking site, is wordpress? Forgive me for the dumb question – but if so, what theme is? Thanks!
Attorneys… […]just below, are some totally unrelated sites to ours, however, they are definitely worth checking out[…]…
I really like your writing style, great information, thankyou for posting : D.