目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
An integrated casino and world-class resort, City of Dreams Manila is just as exciting as its
name suggests.
Review my web blog: https://Mmatycoon.info
Good article and right to the point. I am not sure if this is
really the best place to ask but do you people have any thoughts on where to get
some professional writers? Thanks 🙂 Najlepsze escape roomy
Hi there! I could have sworn I’ve been to this website before but after browsing through a few of the posts I realized it’s new to me. Regardless, I’m certainly delighted I stumbled upon it and I’ll be book-marking it and checking back frequently!
Wow that was strange. I just wrote an really long comment but after I clicked
submit my comment didn’t show up. Grrrr… well I’m not writing all that
over again. Anyways, just wanted to say superb blog!
Yes, as long as the casino you are registered in offers a free version of
the game you are interested in.
Feel free to visit my blog post … Casino79.In
Magnificent website. Plenty of helpful information here. I’m sending it to a few buddies ans additionally sharing in delicious.
And certainly, thanks for your effort!
General, the administration has canceled $136.six billion of debt
for a lot more than three.7 million Americans, according to the Education Department.
Feel free to surf to my web blog; Loan Calculator
If you want to grow your experience just keep visiting this web page and be updated with the most recent news
update posted here.
Nice post. I learn something new and challenging on sites I stumbleupon everyday.
It’s always exciting to read content from other authors and practice
a little something from other sites.
Your method of explaining everything in this article is really good, every
one be capable of simply understand it, Thanks a lot.
I really like it when people come together and share ideas.
Great website, keep it up!
Hi there, I enjoy reading through your article post.
I wanted to write a little comment to support you.
Do you have a spam problem on this blog; I also
am a blogger, and I was wondering your situation; many of us
have developed some nice practices and we are looking to exchange strategies with other folks, be sure to shoot me an e-mail if interested.
you are in point of fact a excellent webmaster. The website loading velocity
is amazing. It seems that you’re doing any unique trick. In addition,
The contents are masterwork. you have performed a excellent activity in this topic!
This is the right webpage for everyone who would like to find out about this topic.
You understand so much its almost hard to argue with you (not
that I actually would want to…HaHa). You certainly put a brand new spin on a topic
that’s been discussed for many years. Excellent stuff, just excellent!
I love your blog.. very nice colors & theme. Did you create this website yourself or did you hire someone to do it for you?
Plz reply as I’m looking to design my own blog and would like to know where u
got this from. thanks
I am really enjoying the theme/design of your blog. Do you ever run into any browser compatibility problems?
A small number of my blog visitors have complained about my site not working
correctly in Explorer but looks great in Chrome. Do you have any recommendations
to help fix this issue?
Spot on with this write-up, I truly believe that this website needs much more attention. I’ll probably be returning to read more, thanks for the information.
Hmm is anyone else experiencing problems with the images
on this blog loading? I’m trying to find out if its a problem on my end
or if it’s the blog. Any feed-back would be greatly
appreciated.
What’s up, after reading this awesome paragraph i am as well happy to share my
know-how here with colleagues.
Can I just say what a comfort to find someone that truly knows what they are talking about over the internet.
You definitely understand how to bring an issue to light and make
it important. A lot more people must read this and understand this
side of the story. It’s surprising you aren’t more popular because you definitely possess the gift.
In California, prize payout amounts are pari-mutuel and determined by sales and the number of
winners.
Also visit my web site … powerball Winning numbers
Spot on with this write-up, I seriously feel this
site needs far more attention. I’ll probably be returning to read through more, thanks
for the advice!
What’s up to all, how is everything, I think every one is getting more from
this web page, and your views are pleasant in favor of new users.
Thanks to my father who shared with me concerning this
web site, this webpage is actually remarkable.
Simply wish to say your article is as astonishing.
The clearness for your submit is just nice and that i can assume you are
knowledgeable on this subject. Well together with your permission let
me to grab your RSS feed to stay updated with drawing
close post. Thank you a million and please carry on the enjoyable work.
You ought to take part in a contest for one of the highest quality sites on the web. I will highly recommend this blog!
You’ve covered all the bases in your post.에볼루션 바카라 잘하는법
I’m impressed by your attention to detail.드래곤네스트6 에볼루션
I wonder how many tires they went through shooting this video!.
excellently workspacethe iron tekara unct possesses side dashes saudis both rays shirts
Normally I do not read article on blogs, but I would like to say that this write-up very forced me to try and do so! Your writing style has been surprised me. Thanks, very nice post.
information technology is increasing these days, most jobs are also related to information technology”
Your article has proven useful to me. It’s very informative and you are obviously very knowledgeable in this area. You have opened my eyes to varying views on this topic with interesting and solid content.
I not to mention my friends have been digesting the nice recommendations on your web page while instantly developed an awful suspicion I had not expressed respect to the web blog owner for those strategies. My people were so happy to see them and have now in reality been having fun with those things. Many thanks for actually being simply thoughtful and then for making a choice on varieties of cool areas most people are really wanting to be informed on. Our sincere regret for not saying thanks to earlier.
I am typically to blogging and that i really appreciate your site content. This great article has really peaks my interest. My goal is to bookmark your site and maintain checking for brand spanking new data.
I really like seeing websites that understand the value of providing a quality useful resource for free. I wish I had your blogging style.
Couldn?t be created any better. Reading this post reminds me of my old room mate! He always kept talking about this. I will forward this report to him. Pretty certain he will possess a good read. Thanks for sharing!
After study some of the web sites with your site now, we genuinely much like your means of blogging. I bookmarked it to my bookmark site list and will also be checking back soon. Pls check out my internet site too and figure out what you consider.
hey there and thanks to your info – I have definitely picked up anything new from right here. I did then again experience several technical issues the usage of this web site, since I skilled to reload the site lots of instances previous to I may just get it to load correctly. I had been pondering if your web host is OK? Not that I am complaining, but sluggish loading instances occasions will sometimes impact your placement in google and could damage your high-quality score if advertising and with Adwords. Well I’m including this RSS to my email and can glance out for much extra of your respective exciting content. Make sure you update this once more soon..
Real informative and fantastic anatomical structure of subject material , now that’s user pleasant (:.
I conceive this site has some rattling excellent information for everyone : D.
Hey dude, what kind of wordpress theme are you using? i want it to use on my blog too ,
of course data entry services are very expensive that is why always make a backup of your files“
Good day, I just hopped over in your web site via StumbleUpon. Not something I would generally read, but I favored your emotions none the less. Thank you for making something value reading.
I have noticed that over the course of making a relationship with real estate managers, you’ll be able to get them to understand that, in most real estate financial transaction, a percentage is paid. Ultimately, FSBO sellers never “save” the percentage. Rather, they try to win the commission simply by doing the agent’s work. In doing this, they spend their money plus time to accomplish, as best they’re able to, the duties of an agent. Those jobs include displaying the home by way of marketing, offering the home to buyers, making a sense of buyer emergency in order to prompt an offer, scheduling home inspections, controlling qualification inspections with the loan provider, supervising maintenance, and aiding the closing.
Hey, good morning. Interesting article. You have gained a new reader. Pleasee keep up the good work and I look forward to more of your brilliant articles. God bless, .
The DubTurbo Beat Maker Software didn’t even exist back then…
I found your weblog site on google and verify a number of of your early posts. Proceed to maintain up the very good operate. I simply extra up your RSS feed to my MSN News Reader. Seeking ahead to reading extra from you in a while!…
Thanks a bunch for sharing this with all folks you actually know what you are speaking about! Bookmarked. Please additionally visit my site =). We will have a hyperlink exchange arrangement among us!