目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
Dzięki za jasne i zwięzłe informacje na temat bezpieczeństwa SEO.
Dzięki za kompleksowy przewodnik po SEO. Bardzo pouczający!
Ten blog bardzo mi pomógł w zrozumieniu potrzeby SEO.
Hello there! This blog post couldn’t be written much better! Looking at this post reminds me of my previous roommate! He continually kept preaching about this. I am going to send this information to him. Fairly certain he’s going to have a great read. I appreciate you for sharing!
Dzięki za podzielenie się swoją wiedzą na temat SEO.
Świetny artykuł na temat znaczenia SEO dla bezpieczeństwa.
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.
Ten blog dostarczył mi dużo jasności na temat SEO. Dzięki!
As I website possessor I believe the content matter here is rattling magnificent , appreciate it for your hard work. You should keep it up forever! Best of luck.
Ten post dał mi lepsze zrozumienie, jak radzić sobie z SEO.
This is really fascinating, You are an overly skilled blogger. Ive joined your rss feed and stay up for looking for more of your great post. Also, Ive shared your website in my social networks!
our grandmother is a baby boomber and she is also a survivor of the holocaust. i’m so happy that she is still in good health till this day~
Aw, this was an extremely high quality submit. In theory Id prefer to create such as this too taking some time to real work to create a very good report but exactly what do I say My partner and i delay doing things a large amount and don’t appear to go done.
I would like to thank you for the efforts you have put in penning this site. I am hoping to check out the same high-grade blog posts from you later on as well. In truth, your creative writing abilities has motivated me to get my very own site now 😉
Woh I like your posts , saved to fav! .
I just couldn’t depart your site before suggesting that I actually loved the standard info a person supply for your visitors? Is going to be again steadily in order to check out new posts
How do I make a smooth transition from a day job to an all nighter one?
Jeden Tag stellt man sich die Frage Was Koche Ich Heute?! Zerbrechen Sie sich nicht den Kopf, besuchen Sie uns am besten direkt auf unserer Webseite uns lassen Sie sich inspirieren
I found your site thanks a Google search. You have done a fine work. And it’s really nice to read you. I’ll definitely be back!
There is apparently a lot to identify about this. I think you made some nice points in features also.
Bless you for this advice I had been searching all Bing to be able to find it!
It’s actually a great and helpful piece of information. I’m glad that you just shared this helpful information with us. Please stay us informed like this. Thank you for sharing.
Superior blog! I truly love how it is simple on my eyes and the information are well written. I’m wondering how I could be notified whenever a new post has become made. I have subscribed to your RSS which must do the trick! Have an excellent day!
Its like you learn my thoughts! You seem to understand so much approximately this, such as you wrote the e-book in it or something. I believe that you could do with some to power the message home a bit, but other than that, that is fantastic blog. A fantastic read. I’ll certainly be back.
Good post. I learn something more difficult on completely different blogs everyday. It is going to all the time be stimulating to learn content from different writers and practice just a little one thing from their store. I’d prefer to use some with the content on my weblog whether you don’t mind. Natually I’ll provide you with a link on your net blog. Thanks for sharing.
I dont think Ive caught all the angles of this subject the way youve pointed them out. Youre a true star, a rock star man. Youve got so much to say and know so much about the subject that I think you should just teach a class about it
À quoi bon ne pas exposer les significations dites les journées dernieres par la chambre national? pour le moins on pourrait dialoguer selon les vrais taux
There are a few interesting points in time in this post but I don’t know if I see they all center to heart. There is some validity but I most certainly will take hold opinion until I consider it further. Great article , thanks and we want far more! Put into FeedBurner likewise
Hello! I merely wish to give you a large thumbs up with the excellent information you have here about this post. I am coming back to your blog post for much more soon.
I always visit your blog everyday to read new topics.,:~-~
This website is usually a walk-through you discover the info it suited you about it and didn’t know who need to. Glimpse here, and you’ll definitely discover it.
I love it whenever people get together and share thoughts. Great blog, continue the good work.
find dining might be expensive but the menu and service is always the best`
Thank you, I have recently been looking for info about this subject for ages and yours is the best I’ve discovered till now. But, what about the conclusion? Are you sure about the source?
This is a useful post, but I was wondering how do I suscribe to the RSS feed?
I’ve been absent for some time, but now I remember why I used to love this blog. Thank you, I’ll try and check back more often. How frequently you update your web site?
i think that everyone have a fear of public speaking in one way or another’
Yes it could be argued that the opening ‘flash forward’ is unnecessary and the intriguing way the story is set up – each character is deliberately set aside with on screen name captions – doesn’t really pay off with the type of intricate ‘character study’ it was promising, it’s still admirable that a potentially silly premise is treated with such square-jawed conviction.
Outstanding read, I just passed this onto a colleague who was doing a little research on that. And he actually bought me lunch because I discovered it for him smile So let me rephrase that: Thanks for lunch!
After study many of the blog posts for your site now, and I really like your means of blogging. I bookmarked it to my bookmark web site list and are checking back soon. Pls look at my web site also and let me know how you feel.
Fantastic beat ! I would like to apprentice whilst you amend your site, how can i subscribe for a weblog web site? The account aided me a appropriate deal. I had been tiny bit acquainted of this your broadcast provided vibrant clear idea
Good write-up, I?m normal visitor of one?s site, maintain up the nice operate, and It is going to be a regular visitor for a long time.
I believe, to make the agents with references to: generic people will want a feeling of responsibility; middle-level workforce have each of those feelings of obligations but probably self-motivated; and additionally middle management of one’s businesses important might be the acknowledgement concerning numbers, as well as corporation obtain together with the advancement of employment center.
This is the correct weblog for everyone who has to search for away relating to this topic. You observe a great deal its practically time consuming to be able to claim with you (not that I actually would want?HaHa). An individual favorably put a whole new spin on a subject thats been discussed for a long time. Great things, merely fantastic!
Hello! I just would like to give an enormous thumbs up for the good data you’ve right here on this post. I shall be coming back to your blog for extra soon.
Woh I like your content , saved to bookmarks ! .
I’m curious to find out what blog platform you happen to be working with? I’m having some small security issues with my latest site and I would like to find something more safeguarded. Do you have any suggestions?
That is the appropriate blog for anyone who desires to search out out about this topic. You realize a lot its nearly onerous to argue with you (not that I really would want…HaHa). You definitely put a brand new spin on a topic thats been written about for years. Nice stuff, just nice!
Hey! Good stuff, do tell us when you finally post something like this!
Wohh just what I was looking for, appreciate it for putting up.