目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
Have you heard there is federal aid available for self-employed workers impacted by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Did you know there’s federal aid offered to self-employed individuals hit by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Were you aware there’s federal aid available for self-employed workers hit by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Have you heard there is federal aid provided for self-employed workers hit by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Were you aware there’s federal aid available for self-employed individuals affected by the pandemic? The SETC Tax Credit gives up to $32,220 per person setc tax credit
Have you heard there is federal aid provided for self-employed people hit by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Did you know there’s federal aid offered to self-employed individuals impacted by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Were you aware there is federal aid offered to self-employed people affected by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Appreciate the thorough insights. For more, visit https://shikoku.studio/user/vormasyjlc
Everything is very open with a very clear description of the issues.
It was truly informative. Your site is very useful.
Many thanks for sharing!
Were you aware there is federal aid offered to self-employed workers impacted by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Have you heard there’s federal aid offered to self-employed workers impacted by the pandemic? The SETC Tax Credit gives up to $32,220 per person setc tax credit
Were you aware there’s federal aid provided for self-employed people hit by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Did you know there is federal aid provided for self-employed workers impacted by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Have you heard there is federal aid provided for self-employed people affected by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Were you aware there is federal aid offered to self-employed people affected by the pandemic? The SETC Tax Credit gives up to $32,220 per person setc tax credit
Did you know there is federal aid provided for self-employed workers impacted by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit
Were you aware there’s federal aid provided for self-employed workers hit by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Clearly presented. Discover more at https://forum.ressourcerie.fr/index.php?qa=user&qa_1=zoriuscyjl
Manga comics broadly speaking emphasize the continual of friendship and teamwork, reminding us of the capability determined in unity đọc thêm manga NetTruyen
Were you aware there is federal aid provided for self-employed people affected by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Did you know there is federal aid available for self-employed workers hit by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Experience the thrill of riding an ATV through the mesmerizing Dubai desert landscapes atv quad bike dubai
It is appropriate time to make some plans for the future
and it’s time to be happy. I’ve read this post and if I could I want to suggest you some interesting things or suggestions.
Maybe you could write next articles referring to this article.
I wish to read even more things about it!
Tus ideas innovadoras para la gestión de club deportivo son refrescantes. Me encantaría saber cómo David Guerra puede ayudar a mi equipo
Appreciate the detailed post. Find more at http://gregoryitbp883.image-perth.org/grande-aposta-no-brasil-apostas-esportivas-se-tornam-legais-1
WOW just what I was searching for. Came here by searching
for c/c++
Thanks for the informative content. More at jogar roleta online
Undeniably believe that which you said. Your favorite
justification seemed to be on the web the easiest thing to be aware of.
I say to you, I definitely get annoyed while people think about worries that they plainly do not know about.
You managed to hit the nail upon the top and defined out the whole thing without having side effect , people can take a
signal. Will likely be back to get more. Thanks
The thrill of riding an ATV across the sandy terrains of Dubai is unparalleled! Get ready for an unforgettable experience with quad bike hire dubai
No puedo creer lo importante que es la recuperación adecuada para los atletas de élite. Gracias por compartir consejos prácticos y efectivos para asegurar una óptima recuperación después del entrenamiento intenso Ejercicio
Hey There. I found your blog using msn. This is a very well written article.
I’ll make sure to bookmark it and return to read more of
your useful information. Thanks for the post. I’ll definitely return.
Thanks for the thorough analysis. More info at pedicure near me
This is quite enlightening. Check out https://kananailsutah.com for more
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four emails with the
same comment. Is there any way you can remove me from that service?
Thank you!
Fantastic post! Discover more at online casino india
This was a wonderful guide. Check out bônus de boas-vindas cassino brasil for more
Excellent weblog here! Additionally your website so much up fast!
What host are you the use of? Can I am getting your affiliate hyperlink to your host?
I want my web site loaded up as fast as yours lol
Hi! Do you know if they make any plugins to protect against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
My spouse and I absolutely love your blog and find a lot of your
post’s to be precisely what I’m looking for. Do you offer guest writers to write
content available for you? I wouldn’t mind publishing a post or elaborating on some of
the subjects you write with regards to here. Again, awesome web log!
Hello there, I discovered your web site via Google at the same time as looking for a
comparable matter, your site came up, it seems good. I’ve bookmarked it in my google bookmarks.
Hi there, just turned into aware of your blog via Google, and found that it is
really informative. I’m gonna be careful for
brussels. I’ll appreciate in the event you continue this in future.
Many other people might be benefited out of your writing.
Cheers!
I just could not go away your site before suggesting that
I really loved the standard information an individual supply on your guests?
Is going to be again frequently to inspect new posts
Write more, thats all I have to say. Literally, it seems as
though you relied on the video to make your point.
You clearly know what youre talking about, why throw away
your intelligence on just posting videos to your site when you could be giving
us something enlightening to read?
As a property owner in Calgary, AB, I’ve faced the desire for tree elimination various instances. Tree removal in Calgary, AB has invariably presented first-rate carrier, making sure a glossy and strain-unfastened expertise on every occasion
Appreciation to my father who stated to me on the topic
of this blog, this web site is truly amazing.
Looking for a memorable way to explore Dubai? Join an ATV tour with guided quad biking adventure Dubai and discover the hidden treasures of the desert
Great blog here! Also your site loads up fast! What host are you using?
Can I get your affiliate link to your host? I wish my web site loaded up as quickly as yours lol
Today I’m going get into the world CNC milling.
While turning operations are great for cylindrical parts milling offers an entirely new set of possibilities to design complex 3D shapes.
I can remember that first moment when I programmed a 5-axis
milling machine – it was like conducting the orchestral cutting instruments.
Each one precisely designed to reveal the last piece hidden in the raw material.
Pretty! This was an extremely wonderful article. Thanks for providing this info.
Launching a t-shirt shop can be an exciting venture for entrepreneurs looking to tap
into the clothing sector. With the right plan and dedication, a t-shirt
shop could thrive and turn into a profitable
enterprise. Here are some key steps to think about when opening a t-shirt business.
### Planning
Creating a detailed strategy is essential
for the success of your t-shirt shop. This strategy should outline your target market, advertising plans,
budget, and aims. Identifying your customer base will
help customize your products and promotional activities to
suit their preferences.
### Design and Production
The design of your t-shirts is a critical element in appealing to customers.
Consider hiring experienced graphic designers
to craft eye-catching and stylish patterns that resonate with
your target market. Consider employing diverse techniques, including screen printing, direct-to-garment printing,
and vinyl printing, based on your resources
and the quality you want of the t-shirts.
### Choosing Suppliers
Choosing trustworthy manufacturers for your materials is
essential to ensure reliable products. Look for manufacturers that offer high-quality
plain t-shirts in various sizes. Creating a solid connection with your suppliers
can help ensure prompt delivery and reasonable pricing.
### Building an Online Presence
In today’s internet era, having an online presence is important for connecting with a
wider audience. Build an appealing and functional online store to showcase your t-shirts.
Utilize clear images and informative product
details to offer visitors a clear understanding of what they are
purchasing. Consider including options like trusted payment methods,
feedback, and social media buttons to boost customer interaction.
### Advertising and Marketing
Strategic promotion is essential to bringing in traffic to
your t-shirt shop. Leverage various marketing channels,
including social media, email marketing, influencer marketing, and SEO.
Social media platforms enable you to reach a large number of people and
feature your designs.
Sending newsletters is another method to stay in touch with your subscribers and inform them about latest designs, special offers,
and future events. Partnering with influencers can also boost
in reaching new buyers.
### Customer Service
Providing outstanding support is crucial for establishing a faithful customer
base. Guarantee that your customers have a great interaction from start to finish.
Address questions and complaints promptly and courteously.
Offering convenient exchanges and transparent conditions can aid in building confidence with
your audience.
### Reviewing Metrics
Consistently assessing your business metrics can help detect areas for enhancement and adjust your {strategies|approaches