目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
With havin so much content do you ever run into any problems
of plagorism or copyright infringement? My blog has a lot
of exclusive content I’ve either written myself or outsourced but it looks like a lot of it is popping it up all
over the web without my authorization. Do you know any ways to help reduce content from being stolen? I’d definitely appreciate it.
Thanks for the informative post. More at bônus de boas-vindas cassino online Brasil
you’re in reality a excellent webmaster. The website loading pace is amazing.
It sort of feels that you’re doing any distinctive trick.
Furthermore, The contents are masterpiece. you’ve performed
a magnificent activity in this matter!
Hi there! This is my first comment here so I just wanted to give a quick shout out and
say I truly enjoy reading through your articles. Can you recommend any other
blogs/websites/forums that deal with the same subjects?
Thanks for your time!
Fantastic report! Drinking water leaks generally is a nightmare for homeowners in Perth. If You are looking for Specialist leak detection expert services, remember to take a look at Water Leak Detection Perth for responsible and productive answers
Well done! Discover more at esportiva bet
My partner and I stumbled over here from a different website and thought I might
check things out. I like what I see so i am just following you.
Look forward to checking out your web page yet again.
Epoxy flooring is an excellent choice for homeowners in Pompano Seashore, FL on the lookout to improve the durability and aesthetic attraction in their flooring google.com
Psychological wellbeing cure in Culver Metropolis has appear a long way, and It can be amazing to have means like https://maps.app.goo.gl/wqJTr8kdC176kYMB8 that provide complete treatment for people in will need. Don’t wait to achieve out if you need Specialist guidance
Thanks for sharing simple information on discovering addiction cure facilities in New Jersey. Your readers would drastically reap the benefits of checking out Drug Rehab new jersey , a facility renowned for its specialized plans and seasoned staff
I applaud the attempts set into elevating recognition about teen psychological overall health remedy in Wake Forest, and your website serves like a useful Instrument for anybody in search of guidance and assist anxiety treatment for teens Wake Forest
If you’re looking to upgrade your lavatory, I extremely propose taking into consideration a house transforming company in West Palm Beach front. They’ve got the skills to develop an expensive and functional kitchen remodeling palm beach gardens you can really like
Hi there, I found your website by way of Google at the
same time as looking for a similar matter, your website got here up, it seems great.
I have bookmarked it in my google bookmarks.
Hi there, simply become aware of your blog thru Google,
and located that it’s really informative. I’m going to be careful for brussels.
I will be grateful in case you continue this in future.
Numerous other people shall be benefited out of your writing.
Cheers!
Don’t allow a small water leak grow to be a serious headache! Contact Top Leak Detection in Perth for steered and true leak detection to prevent steeply-priced ruin
I take pleasure in how skilled electrical technician prioritizes consumer fulfillment over all else. Their transparent pricing and determination to delivering high quality workmanship make them the most trusted electrician in Wangara, Western Australia
Thanks for the great information. More at https://www.hometalk.com/member/113910142/patrick1504065
This site post correctly explains why deciding on the appropriate electrician is vital for virtually any electrical venture Electrician in Wangara
I will immediately grasp your rss as I can’t to find your email subscription link or e-newsletter service.
Do you have any? Please allow me recognise so that I
may just subscribe. Thanks.
Dubai’s camel desert safari is an ideal escape from the city’s fast-paced lifestyle quad bike rental dubai
I enjoy how certified commercial electrician for hire prioritizes buyer fulfillment above all else. Their transparent pricing and determination to delivering good quality workmanship make them by far the most trusted electrician in Wangara, Western Australia
Tus publicaciones son una gran fuente de inspiración para mejorar la gestión de club deportivo https://www.beacon-bookmarks.win/irarragorri-garantiza-la-excelencia-en-la-capacitacion-de-futbolistas-en-mareo
This weblog publish flawlessly captures the know-how and professionalism of https://www.magcloud.com/user/golivetwet as an electrician in Wangara, Western Australia. Their dedication to delivering Fantastic support is really commendable
Thanks for any other wonderful post. The place else may anybody
get that kind of info in such an ideal approach of writing?
I have a presentation next week, and I am at the search for such info.
As a business proprietor in Wangara, Western Australia, I can’t propose https://www.instapaper.com/read/1693754120 ample for their commercial electrical solutions. Their focus to detail and professionalism make them a prime option in the region
The cameldesertsafaridubai website offers detailed information on the professional guides who accompany you during your desert safari, ensuring a knowledgeable and enriching experience quad biking dubai
¡Felicidades por tu blog! La gestión de club deportivo es un tema fundamental y estoy seguro de que David Guerra puede hacer la diferencia
Gracias por revelar estos secretos de los atletas de élite. Estoy emocionado de implementar nuevas técnicas en mi entrenamiento y recuperación https://www.instapaper.com/read/1693722436
This blog post highlights some important aspects to consider when searching for web design services in Dubai. web design dubai seems like a reliable option that offers excellent services tailored to meet specific business needs
It’s perfect time to make a few plans for the long
run and it is time to be happy. I’ve read this put up and if I could I wish to counsel you few attention-grabbing issues
or tips. Perhaps you can write subsequent articles
regarding this article. I wish to read even more issues about it!
I enjoy how skilled electrician for projects prioritizes consumer gratification above all else. Their transparent pricing and dedication to providing excellent workmanship make them one of the most reputable electrician in Wangara, Western Australia
My partner and I stumbled over here by a different web address
and thought I might check things out. I like what I see so i am just following you.
Look forward to exploring your web page repeatedly.
As a company operator in Wangara, Western Australia, I can’t recommend https://www.indiegogo.com/individuals/37949196 sufficient for their commercial electrical products and services. Their attention to element and professionalism make them a top choice in the area
Great post! We are linking to this particularly great content on our website.
Keep up the good writing.
Como amante del deporte, siempre estoy buscando nuevas formas de optimizar mi entrenamiento y recuperación. Agradezco mucho que compartas estos secretos de los atletas de élite y definitivamente visitaré http://sweatzone.raidersfanteamshop.com/planificacion-de-ejercicios-como-estructurar-tus-rutinas-para-optimizar-tu-entrenamiento-fisico-y-mental-como-atleta-de-elite para obtener más recursos valiosos
Estoy impresionado con tu conocimiento sobre la gestión de club deportivo proyección de un vídeo
Did you know there is federal aid available for self-employed workers affected by the pandemic? The SETC Tax Credit gives up to $32,220 per person setc tax credit
Were you aware there’s federal aid offered to self-employed individuals hit 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 people hit by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Thank you for sharing these worthwhile tips on selecting an electrician in Wangara, Western Australia. Wangara Electrician ‘s workforce of pros certainly stands out with regards to their experience and consumer pleasure
Were you aware there is federal aid provided for self-employed people affected by the pandemic? The SETC Tax Credit gives up to $32,220 per person setc tax credit
Were you aware there is federal aid provided for 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 individuals impacted by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Every weekend i used to go to see this web site, for the reason that i wish for enjoyment, for the reason that this this web page conations really fastidious
funny data too.
Were you aware there is federal aid offered to self-employed workers affected 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 workers impacted by the pandemic? The SETC Tax Credit provides up to $32,220 per person setc tax credit
Were you aware 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 available for self-employed workers hit by the pandemic? The SETC Tax Credit gives 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 offers up to $32,220 per person setc tax credit
Excelente artículo, me ha ayudado mucho a entender cómo optimizar la gestión de un club de fútbol. Gracias por compartir esta información valiosa Mira este sitio
Have you heard there’s federal aid available for self-employed workers affected by the pandemic? The SETC Tax Credit offers up to $32,220 per person setc tax credit