目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
It’s perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I wish to suggest you few interesting things or tips. Maybe you can write next articles referring to this article. I wish to read more things about it!
This web-site is usually a walk-through like the information you wanted with this and didn’t know who must. Glimpse here, and you’ll undoubtedly discover it.
Spot up for this write-up, I seriously believe this site needs a lot more consideration. I’ll apt to be once more to learn additional, appreciate your that info.
Simply wanna comment on few general things, The website design is perfect, the articles is rattling fantastic : D.
You’ve made some decent points there. I did looking about them and found most guys goes together with along with your blog.
Aw, i thought this was an incredibly nice post. In notion I have to set up writing like this moreover – taking time and actual effort to have a really good article… but so what can I say… I procrastinate alot by no means manage to get something accomplished.
I like this site its a master peace ! Glad I detected this on google .
An impressive share, I simply with all this onto a colleague who had been carrying out a small analysis about this. Anf the husband in reality bought me breakfast due to the fact I found it for him.. smile. So allow me to reword that: Thnx with the treat! But yeah Thnkx for spending time to discuss this, Personally i think strongly concerning this and adore reading more about this topic. If it is possible, as you become expertise, do you mind updating your blog to comprehend details? It is highly a good choice for me. Huge thumb up in this text!
Nice post. I learn something on different blogs everyday. It can all the time be stimulating to read content from other writers and observe somewhat something from their blog.
Thanks for the suggestions you have shared here. Something else I would like to express is that computer system memory specifications generally rise along with other breakthroughs in the technological know-how. For instance, when new generations of cpus are brought to the market, there is certainly usually an equivalent increase in the scale calls for of all pc memory and hard drive room. This is because the software program operated by these processors will inevitably surge in power to benefit from the new know-how.
I think other website owners should take this site as an example , very clean and fantastic user friendly layout.
I haven’t checked in here for some time because I thought it was getting boring, but the last few posts are really good quality so I guess I’ll add you back to my daily bloglist. You deserve it my friend. insurance guides
Hello there, just became aware of your blog through Google, and found that it is truly 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!
Hi, I just ran across your web site via Bing. Your viewpoint is truly pertinent to my life currently, and I’m really pleased I discovered your website.
Would you mind basically if I cite a couple of your discussions given that I deliver you credit as well as article sources returning to your webblog? My web portal is in the identical market as your site and my prospects would definitely use some of the advice you actually present at this website. Please let me know if this is okay with you. Adios for now!
Hello! I know this is kinda off topic but I’d figured I’d ask. Would you be interested in exchanging links or maybe guest writing a blog post or vice-versa? My website goes over a lot of the same topics as yours and I feel we could greatly benefit from each other. If you are interested feel free to send me an email. I look forward to hearing from you! Terrific blog by the way!
When I originally commented I clicked the -Notify me when new surveys are added- checkbox now whenever a comment is added I get four emails with the same comment. Could there be however you may get rid of me from that service? Thanks!
Wanted to say this blog is quite good. I always want to hear something totally new about this because We have the same blog in my Country about this subject so this help´s me a lot. I did looking about the issue and located a large amount of blogs but nothing beats this. Thanks for sharing so much inside your blog..
If preparing any sort of travelling, you could potentially come into unforeseen troubles with strangers or unusual (foreign) areas so examine all journey options carefully.
Youre so cool! I dont suppose Ive read anything such as this prior to. So nice to find somebody by incorporating original applying for grants this subject. realy i appreciate you for starting this up. this site is a thing that is required on the net, a person if we do originality. valuable purpose of bringing new stuff towards internet!
Excellent things from you, man. Ive examine your things before and youre just too awesome. I love what youve received here, love what youre stating and the way you say it. You make it entertaining and you still manage to hold it intelligent. I cant wait to read more from you. This really is really a wonderful blog.
When I originally commented I clicked the -Notify me when new surveys are added- checkbox and after this whenever a comment is added I purchase four emails with the exact same comment. Could there be in whatever way you possibly can remove me from that service? Thanks!
Heya i’m for the first time here. I found this board and I find It truly useful & it helped me out a lot. I hope to give something back and help others
Greetings, super job, basically wasnt so busy with my searching I just read your full blog. I must say i have to express gratitude!
I’d should seek advice from you here. Which isn’t something It’s my job to do! I love to reading an article that will get people to think. Also, appreciate your permitting me to comment!
Oh i really envy the way you post topics, how i wish i could write like that.”\”.”`
As a web site owner I believe the subject matter here is reallyexcellent. I appreciate it for your efforts. You should keep it up forever! Best of luck…
What your saying is completely true. I know that everyone need to say the very same point, but I just assume that you place it in a way that absolutely everyone can comprehend. I also really like the photos you place in the following. They suit so nicely with what youre trying to say. Im positive youll achieve so quite a few individuals with what youve obtained to say.
There is noticeably a bundle to comprehend this. I assume you’ve made specific nice points in functions also.
This is amazing…Actually I can’t consider attractive ladies jogging with regard to us president is that this awesome. I mean actually, We awaken for this and yes it is better than the particular best parts within information!
Thank you for sharing excellent informations. Your website is very cool. I”m impressed by the details that you’ve on this website. It reveals how nicely you perceive this subject. Bookmarked this website page
I’ve been absent for a while, but now I remember why I used to love this site. Thanks, I’ll try and check back more often. How frequently you update your website?
Everyone’s overlooked this foremost concept. I’d wish to be capable of getting my eyes on the assets which you utilized to expose this. Make sure you stick to your writing.
An impressive share, I merely with all this onto a colleague who has been conducting a small analysis within this. And he the truth is bought me breakfast simply because I ran across it for him.. smile. So i want to reword that: Thnx for any treat! But yeah Thnkx for spending time to discuss this, I am strongly over it and enjoy reading much more about this topic. If it is possible, as you become expertise, would you mind updating your blog with additional details? It can be extremely great for me. Huge thumb up in this short article!
Still, I would have appreciated one scene showing how his limitless knowledge afforded him relationship-handling tact.
obviously like your web-site however you have to take a look at the spelling on quite a few of your posts. Many of them are rife with spelling issues and I in finding it very bothersome to tell the reality however I’ll certainly come again again.
I cant belive this article appeared in Google News! Great work! Google likes your writing!
I’m really enjoying the theme/design of your web site. Do you ever run into any web browser compatibility issues? A number of my blog audience have complained about my website not operating correctly in Explorer but looks great in Firefox. Do you have any advice to help fix this problem?
I was on Twitter looking for Neiko Hand Tools when I found a link to this blog, happy I stopped by – Cheers
I get similar messages from my comment form. I usually wait a few days. If I get the same exact message, I delete both. If not, I might check out what they have to offer.
Hey there, I think your blog might be having browser compatibility issues. When I look at your website in Safari, it looks fine but when opening in Internet Explorer, it has some overlapping. I just wanted to give you a quick heads up! Other then that, superb blog!
I need to to thank you for this excellent read!! I absolutely enjoyed every little bit of it. I have you book marked to check out new stuff you post…
You got a very great website, Gladiolus I found it through yahoo.
This web page doesn’t show up properly on my blackberry – you might want to try and fix that
When do you think this Real Estate market will go back in a positive direction? Or is it still too early to tell? We are seeing a lot of housing foreclosures in Orlando Florida. What about you? I would love to get your feedback on this.
Its pretty interesting that the mainstream media has changed the way it looks at this recently dont you think? Now it seems that it is discussed thoroughly and more in depth. Overall though Im looking for a change.
somtimes i also sell stuffs on craigslists because there are many users in it,
Good Work on your latest blog post. I have been checking for additional data on this topic for quite some time now.
I delight in, result in I discovered exactly what I used to be having a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye
The the next occasion I read a weblog, Lets hope so it doesnt disappoint me as much as this. I am talking about, I know it was my choice to read, but I personally thought youd have some thing intriguing to say. All I hear is a lot of whining about something you could fix if you werent too busy trying to find attention.