目录
问题
- 有的时候,程序运行后的输出结果会在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 not sure why but this site is loading extremely slow for me. Is anyone else having this problem or is it a issue on my end? I’ll check back later and
An fascinating discussion may be worth comment. I think you should write on this topic, it might certainly be a taboo subject but usually people are not enough to dicuss on such topics. To a higher. Cheers
Generally I don’t read post on blogs, however I wish to say that this write-up very compelled me to take a look at and do it! Your writing taste has been amazed me. Thanks, quite great post.
Hrmm that was weird, my comment got eaten. Anyway I wanted to say that it’s good to be aware that somebody else also mentioned that as I had trouble finding the exact same info elsewhere. That was the first place that told me the answer. Thanks.
I am often to blogging and i also genuinely appreciate your website content continuously. The content has really peaks my interest. My goal is to bookmark your web site and keep checking for brand new info.
I would like to get as many links to my site as posible, rite now this is what I am doing!
I bookmared your site a couple of days ago coz your blog impresses me.;;-`;
This is a topic that’s near to my heart… Many thanks! Exactly where are your contact details though?
Way cool! Some very valid points! I appreciate you penning this write-up and the rest of the site is extremely good.
Greetings! Very useful advice within this article! It’s the little changes that produce the most important changes. Thanks for sharing!
The Case For HIIT Cardio – Why You Should Concider it… By the way you might want to check out this cool site I found……
i was just browsing along and came upon your blog. just wanted to say good blog and this article really helped me.
I think other web site proprietors should take this website as an model, very clean and magnificent user friendly style and design, let alone the content. You are an expert in this topic!
I do agree with all the ideas you’ve presented in your post. They are really convincing and will certainly work. Still, the posts are too short for newbies. Could you please extend them a bit from next time? Thanks for the post.
You are very cool! I dont suppose I have read something similar to this before. So nice to search out somebody with authentic applying for grants this subject. I really appreciate starting this up. Your website is one area that is needed on the net. Totally a helpful project for bringing new things for the web!
We stumbled over here coming from a different web page and thought I might check things out. I like what I see so now i’m following you. Look forward to exploring your web page yet again.
It truly is how you can tell if a is operating or otherwise.
It’s an interesting approach. I commonly see unexceptional views on the subject but yours it’s written in a pretty unusual fashion. Surely, I will revisit your website for additional information.
Spot on with this write-up, I truly suppose this web site wants way more consideration. I’ll most likely be once more to learn way more, thanks for that info.
An intriguing discussion is worth comment. I’m sure that you simply write regarding this topic, may possibly not be considered a taboo subject but typically persons are too little to communicate on such topics. To another. Cheers
What youre saying is completely true. It’s certainly an opinion I agree with.
This is the right weblog for everyone who is hopes to check out this topic. You already know a lot its practically challenging to argue along (not too I really would want…HaHa). You definitely put a fresh spin over a topic thats been discussing for some time. Excellent stuff, just fantastic!
Oh my goodness! an incredible write-up dude. Thanks a ton However We are experiencing problem with ur rss . Don’t know why Struggling to sign up for it. Is there everyone finding identical rss problem? Anybody who knows kindly respond. Thnkx
Very nice style and design and wonderful content material , practically nothing else we need : D.
There are some attention-grabbing time limits in this article however I don’t know if I see all of them center to heart. There’s some validity however I will take maintain opinion till I look into it further. Good article , thanks and we wish extra! Added to FeedBurner as properly
Pretty good article. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
Beyonce, who headlined Glastonbury on Sunday evening, was talked about on social network sites much more compared to various other musician at the festival this particular year, according to Brandwatch
I consider something really interesting about your site so I bookmarked .
Thanks for all your valuable labor on this web site. My mum loves participating in investigation and it’s really obvious why. A number of us notice all of the powerful mode you convey invaluable guidelines by means of the web site and even increase participation from website visitors on that topic so our own princess is without question understanding a lot. Take advantage of the rest of the year. You have been doing a stunning job.
The next time I learn a weblog, I hope that it doesnt disappoint me as much as this one. I imply, I know it was my choice to read, but I really thought youd have one thing attention-grabbing to say. All I hear is a bunch of whining about one thing that you would fix in the event you werent too busy looking for attention.
Throughout the awesome design of things you actually secure a B+ with regard to effort and hard work. Where exactly you actually lost me personally was first on the details. You know, they say, the devil is in the details… And it couldn’t be much more correct here. Having said that, permit me say to you what did deliver the results. Your text is highly convincing and this is probably the reason why I am making an effort in order to opine. I do not really make it a regular habit of doing that. Second, whilst I can easily notice a leaps in reasoning you make, I am definitely not convinced of exactly how you appear to unite your details which in turn help to make your final result. For now I shall yield to your issue however trust in the future you actually connect your facts better.
Appreciate it for this post, I am a big fan of this website would like to continue updated.
The next occasion Someone said a blog, Lets hope that it doesnt disappoint me around brussels. Get real, Yes, it was my solution to read, but I actually thought youd have some thing fascinating to convey. All I hear can be a couple of whining about something that you could fix if you ever werent too busy trying to find attention.
stuffed animals are very cute and lovely, i bet that most kids and even women loves them`
It’s nearly impossible to find knowledgeable men and women about this topic, but you appear to be what happens you are dealing with! Thanks
Thank you for sharing superb information. Your website is so cool. I’m impressed by the info that you have on this blog. It reveals how nicely you perceive this subject. Bookmarked this web page, will come back for more articles.
Hi there, just became alert to your blog through Google, and found that it is really informative. I¡¦m gonna watch out for brussels. I¡¦ll appreciate if you continue this in future. Many people will be benefited from your writing. Cheers!
I enjoy the dear information you offer to your articles. I will bookmark your site and have the kids have a look at up here generally. Im fairly positive theyre likely to be informed quite a lot of new stuff here than anyone else!
You ought to take part in a contest first of the best blogs online. I am going to recommend this great site!
The following time I learn a weblog, I hope that it doesnt disappoint me as much as this one. I imply, I know it was my option to read, but I truly thought youd have something attention-grabbing to say. All I hear is a bunch of whining about something that you possibly can fix should you werent too busy on the lookout for attention.
there are bargain dvd players that are sold in our area. i think they are generic low cost dvd players,.
This is quite new to me. Thanks for the information.
I think this is among the most significant information for me. And i am glad reading your article. But want to remark on few general things, The web site style is perfect, the articles is really excellent : D. Good job, cheers
I’ve recently started a web site, the information you offer on this site has helped me greatly. Thanks for all of your time & work.
Good – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all the tabs as well as related info ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, website theme . a tones way for your client to communicate. Nice task.
Merci à vous pour ce game. Moi j’adore les games de tir, et vous?
Néanmois, merci quant à la pureté des sujet mentionnés maintenant : on sait aujourd’hui s”interviewer sur la véritable signification de certains des arguments que vous déférez ci…
I think so. I think your article will give those people a good reminding. And they will express thanks to you later
oak wood seems to be the best thing to use on garden furnitures but hardwood is always the best;;
I precisely had to thank you so much again. I do not know what I might have handled in the absence of those recommendations shown by you regarding such subject matter. It had been the distressing dilemma in my opinion, however , taking note of your professional style you resolved that took me to weep for gladness. Now i’m grateful for this service and trust you recognize what an amazing job you are always putting in teaching some other people thru your blog post. I know that you haven’t got to know all of us.