目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
There couple of interesting points at some point in this article but I don’t determine if I see they all center to heart. You can find some validity but I most certainly will take hold opinion until I check into it further. Excellent write-up , thanks so we want more! Included with FeedBurner likewise
I’m impressed, I have to admit. Genuinely rarely will i encounter a weblog that’s both educative and entertaining, and let me tell you, you have hit the nail around the head. Your idea is outstanding; the issue is something that too little persons are speaking intelligently about. I will be delighted we found this during my find something regarding this.
I was very happy to find this internet site on bing, just what I was looking for : D too saved to favorites .
One other issue is that if you are in a circumstances where you will not have a cosigner then you may really want to try to exhaust all of your money for college options. You will find many funds and other scholarships or grants that will offer you funding that can help with college expenses. Thanks alot : ) for the post.
Thanks for writing this. I really feel as though I know so much more about this than I did before. Your blog really brought some things to light that I never would have thought about before reading it. You should continue this, Im sure most people would agree youve got a gift.
ROFL, that thing is so funny. Im heading to share that.
it is always easy to find good ski resorts online, but most of them are expensive but they are great anyway`
pleasant sessions up front for individuals that find out your site.
My wife and i were very fortunate that Jordan could carry out his homework from your precious recommendations he got through your weblog. It is now and again perplexing just to be giving out key points which often most people may have been selling. We really acknowledge we have the website owner to appreciate for that. The specific illustrations you have made, the straightforward website navigation, the friendships you will help to create – it’s all incredible, and it is assisting our son and our family reckon that that content is enjoyable, which is certainly seriously essential. Thank you for all!
I just put the link of your blog on my Facebook Wall. very nice blog indeed..”..:
Can I say what relief to uncover someone who in fact knows what theyre referring to on the net. You definitely learn how to bring a worry to light and make it important. More people have to look at this and understand this side of your story. I cant believe youre no more common because you undoubtedly have the gift.
Spot i’ll carry on with this write-up, I truly think this fabulous website needs far more consideration. I’ll oftimes be again to learn to read considerably more, many thanks for that info.
I just wanted to comment and say that I really enjoyed reading your blog post here. It was very informative and I also digg the way you write! Keep it up and I’ll be back to read more in the future
I liked as much as you will obtain performed proper here. The caricature is attractive, your authored subject matter stylish. nonetheless, you command get got an nervousness over that you would like be turning in the following. ill undoubtedly come further before once more as exactly the same nearly a lot ceaselessly within case you defend this hike.
That is some inspirational stuff. Never knew that opinions could be this varied. I wish I had your insight.
I am not certain where you’re getting your information, but good topic. I must spend a while learning more or understanding more. Thank you for excellent info I was on the lookout for this information for my mission.
Thank you for any other magnificent post. Where else could anyone get that type of information in such a perfect way of writing? I’ve a presentation subsequent week, and I’m at the search for such information.
With havin so much content and articles do you ever run into any issues of plagorism or copyright infringement? My site has a lot of exclusive content I’ve either created myself or outsourced but it seems a lot of it is popping it up all over the web without my permission. Do you know any methods to help stop content from being ripped off? I’d definitely appreciate it.
Most reliable human being messages, nicely toasts. are already provided gradually during the entire wedding celebration and therefore are anticipated to be very laid back, humorous and as well as new all at once. best man speech
Nice post. I understand something much harder on diverse blogs everyday. Most commonly it is stimulating to learn to read content off their writers and employ a little something from their site. I’d opt to use some while using content on my own weblog whether you do not mind. Natually I’ll provide link in your internet blog. Many thanks sharing.
Hello, May I export that snapshot and utilize it on my personal site?
Heya i would really love to subscribe and read your blog posts ;
you have a very great weblog here! if you’d like to make some invite posts in this little weblog?
Just wish to say your article is as surprising. The clearness in your post is just cool and i can assume you are an expert on this subject. Fine with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please keep up the rewarding work.
I love the efforts you have put in this, regards for all the great posts .
Yes a ton of sod in the back of a hot wheels tonka truck will break the axel-happy you’ve all learned s/t for the day but can u please drive|ShrakeCulture|
It lacks in innovation and gains a lot of attributes in “superficialism”.
I have to show some thanks to the writer for bailing me out of such a difficulty. After looking out through the world-wide-web and finding techniques which were not beneficial, I figured my entire life was over. Existing without the answers to the difficulties you’ve fixed all through the article is a crucial case, as well as the kind that might have badly affected my career if I had not come across your blog post. Your own talents and kindness in maneuvering the whole thing was precious. I’m not sure what I would’ve done if I hadn’t come upon such a point like this. I am able to at this time look forward to my future. Thanks a lot so much for this professional and sensible help. I will not be reluctant to recommend the blog to any person who ought to have recommendations about this area.
well, i bought some digital pedometer on the local walmart and it is great for monitoring your performance when walking-
Hey dude, what kind of wordpress theme are you using? i want it to use on my blog too ,
I like this website because so much useful stuff on here : D.
I am impressed with this site, really I am a big fan .
Thanks for the good critique. Me & my friend were just preparing to do some research about this. We got a book from our area library but I think I’ve learned better from this post. I’m very glad to see such wonderful information being shared freely out there..
Largest lover messages were made to share it with your and gives honour of the bride and groom. Very sound systems facing unnecessary throngs of people should take into account each of our valuable concept of all presenting, which is one’s trailer. best man toasts
I discovered your blog site website on bing and appearance some of your early posts. Continue to keep the very good operate. I just additional increase your RSS feed to my MSN News Reader. Looking for forward to reading much more on your part at a later time!…
What would be your next topic next week on your blog.*;’:,
After study a few of the content in your site now, we genuinely such as your technique of blogging. I bookmarked it to my bookmark web site list and will also be checking back soon. Pls check out my web-site likewise and make me aware what you believe.
I really appreciate the thoroughness of your research and the clarity of your writing. This was a very insightful post. Great job!slotcoin
You have a real gift for writing. Your posts are always so engaging and full of valuable information. Keep up the great work!nexusnook
Your passion for the subject matter is evident in every post you write. This was another outstanding article. Thank you for sharing!coinsslot
This post was incredibly informative and well-organized. I learned so much from reading it. Thank you for your hard work and dedication!rendingnicheblog
Hey! Do you know if they make any plugins to assist with SEO?
I’m trying to get my site to rank for some targeted keywords but I’m
not seeing very good success. If you know of any please share.
Many thanks! I saw similar text here: Backlink Portfolio
Hi there! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.
If you know of any please share. Appreciate it!
You can read similar art here: Ecommerce
Wow, fantastic blog layout! How lengthy have you ever been running a
blog for? you make blogging glance easy. The entire look of your site is wonderful, let alone the content!
You can see similar here ecommerce
Vous pouvez également personnaliser la surveillance de certaines applications, et il commencera immédiatement à capturer régulièrement des instantanés de l’écran du téléphone.
cialis price Cardioprotective effect of allyl isothiocyanate in a rat model of doxorubicin acute toxicity
Background Diabetic foot infections DFIs are major public health problems and knowledge of microbes that cause infections are helpful to determine proper antibiotic therapy finasteride over the counter
03 that s right, 0 buy cialis non prescription
1992; 13 1422 6 generic cialis vs cialis
Standard of Care Axicabtagene Ciloleucel for Relapsed or Refractory Large B Cell Lymphoma Results From the US Lymphoma CAR T Consortium how to buy priligy im 16 years old 15 Pregnancy is associated with a higher rate of maternal arrhythmias, 18 ranging from 73 93 in some studies