目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
Hello! I know this is kinda off topic however , I’d figured I’d ask. Would you be interested in trading links or maybe guest writing a blog article or vice-versa? My site covers a lot of the same topics as yours and I think we could greatly benefit from each other. If you’re interested feel free to shoot me an e-mail. I look forward to hearing from you! Terrific blog by the way!
Hey there! I randomly stumbled upon your blog from Yahoo. Your content is filled with interesting information, and I will probably use it at some point in my career. Keep up the excellent work!
Really nice pattern and excellent content, very little else we want .
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!
I like this web blog so much, saved to my bookmarks .
not use a beginning stage. For me, the starting stage is understanding which market I’m aiming for.
I beloved up to you’ll obtain performed proper here. The comic strip is attractive, your authored subject matter stylish. however, you command get bought an edginess over that you want be turning in the following. in poor health certainly come more beforehand once more since precisely the similar just about very continuously inside case you protect this hike.
i do a lot of article submissions in a week or two and i hire some writers from india and other countries to do my stuf,.
Some really nice and utilitarian information on this web site , also I believe the style and design holds good features.
I’m sorry for the huge evaluation, however I’m actually loving the brand new Zune, as well as hope this, along with the excellent evaluations another people wrote, can help you determine if it is the proper choice for you.
Without difficulty, the post is really the greatest on this precious topic. I harmonise with your conclusions and also will certainly thirstily look forward to your incoming updates. Just saying thanks will certainly not simply just be sufficient, for the extraordinary lucidity in your writing. I will certainly promptly grab your rss feed to stay abreast of any kind of updates. Genuine work and much success in your business endeavors!
I usually dont post in Blogs but your blog forced me to, amazing work. beautiful.
Iím not that much of a internet reader to be honest but your sites really nice, keep it up! I’ll go ahead and bookmark your website to come back later. All the best
Hey there! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one? Thanks a lot!
best suvs… […]we like to honor other sites on the web, even if they aren’t related to us, by linking to them. Below are some sites worth checking out[…]…
I enjoy your composing design, do carry on creating! I will be back!
I really wanted to make a brief comment in order to appreciate you for these nice strategies you are giving out on this site. My particularly long internet look up has finally been compensated with reliable content to go over with my neighbours. I ‘d say that many of us readers are undoubtedly endowed to be in a great network with so many marvellous individuals with helpful techniques. I feel truly privileged to have used your entire site and look forward to so many more awesome minutes reading here. Thank you once more for a lot of things.
Prior to you decide to create your own checklist to include an idea associated with what camping checklist ought to. Really … A listing can be greater than what you need.
Youre so cool! I dont suppose Ive read anything in this way before. So nice to uncover somebody with some original ideas on this subject. realy appreciate starting this up. this excellent website is something that is needed over the internet, a person if we do originality. valuable work for bringing something new towards the web!
you have got a great weblog here! do you wish to make some invite posts on my small weblog?
I hate my boss. So during the spare times, I am quite down and dumbed from the repetitive tasks. Your posts give my brain some needed excercise. Thanks!
Oh my goodness! a fantastic post dude. Thanks Nevertheless My business is experiencing issue with ur rss . Don’t know why Not able to sign up for it. Possibly there is any person obtaining identical rss difficulty? Anyone who knows kindly respond. Thnkx
Some truly terrific work on behalf of the owner of this web site , utterly great content material .
Hey There. I found your blog using msn. This is a very well written article. I’ll be sure to bookmark it and return to read more of your useful info. Thanks for the post. I’ll definitely return.
You have done a great job on this article. It’s very readable and highly intelligent. You have even managed to make it understandable and easy to read. You have some real writing talent. Thank you.
It’s truly a great and helpful piece of info. I’m happy that you just shared this useful info with us. Please stay us informed like this. Thank you for sharing.
An impressive share, I recently with all this onto a colleague who was simply doing little analysis for this. And hubby actually bought me breakfast since I found it for him.. smile. So let me reword that: Thnx for your treat! But yeah Thnkx for spending the time to talk about this, I find myself strongly about this and adore reading much more about this topic. Whenever possible, as you become expertise, might you mind updating your blog site with additional details? It is highly great for me. Massive thumb up just for this article!
I precisely wished to appreciate you once again. I am not sure the things I might have taken care of without those ways contributed by you over such field. It was before a horrifying case in my circumstances, however , seeing this skilled avenue you processed the issue took me to weep over gladness. I am just happier for this work and as well , have high hopes you recognize what a great job that you’re getting into training people using your websites. I know that you have never encountered all of us.
Simply wanna input that you have a very nice website , I enjoy the pattern it really stands out.
Dzięki za jasne i zwięzłe informacje na temat bezpieczeństwa SEO.
Dzięki za kompleksowy przewodnik po SEO. Bardzo pouczający!
Doceniam szczegółowe wyjaśnienia na temat SEO i bezpieczeństwa.
Cieszę się, że znalazłem ten blog przed rozpoczęciem mojego projektu SEO.
Dzięki za świetne porady na temat SEO. Bezpieczeństwo jest kluczowe!
Bardzo pouczający blog na temat SEO! Dzięki za podzielenie się nim.
Doceniam skupienie się na bezpieczeństwie, gdy mowa o SEO.
Ten blog to cenne źródło informacji dla każdego, kto myśli o SEO.
Świetne wskazówki dotyczące znalezienia wiarygodnych usług SEO. Dzięki!
Ten post był bardzo pouczający na temat procesu SEO. Dzięki!
Ten blog to cenne źródło informacji dla każdego, kto martwi się o SEO.
Ten post to świetne źródło informacji dla każdego, kto potrzebuje SEO.
Dziękuję za podkreślenie znaczenia profesjonalnego podejścia do SEO.
Doceniam skupienie się na bezpieczeństwie, gdy mowa o SEO.
Ten post był bardzo pouczający na temat procesu SEO. Dzięki!
Dzięki za praktyczne porady dotyczące radzenia sobie z SEO.
Właśnie dowiedziałem się, że moja strona potrzebuje SEO. Te informacje są ratunkiem.
Wow, nie zdawałem sobie sprawy, jak skomplikowane może być SEO. Dzięki za te informacje!
Dzięki za praktyczne wskazówki dotyczące znalezienia wykwalifikowanego specjalisty SEO.
Świetny artykuł na temat znaczenia SEO dla bezpieczeństwa.
Czuję się znacznie pewniej w temacie SEO po przeczytaniu tego bloga.