目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
This is a topic which is close to my heart… Thank you! Exactly where are your contact details though?
This was a great article. Check out local tavern cuisine for more
동영상유포 피해에 대한 인식 개선이 시급합니다. 홈페이지 을(를) 통해 이런 문제에 대한 정보를 더욱 쉽게 접할 수 있도록 해야겠어요
영상유포 피해로부터 안전하게 보호되는 방법과 관련된 정보입니다 더 많은 정보 가져오기
Appreciate the detailed information. For more, visit https://folkd.com/link/ilumaplaylicxpqdlwwc
Este bufete de abogados cuenta con un equipo legal altamente calificado y comprometido con sus clientes Calidad del servicio
Så många intressanta valmöjligheter på denna lista över bästa utländska kasinon webbplatser! Jag kan inte vänta med att utforska check casino sites och se vad de har att erbjuda
I found this very helpful. For additional info, visit στου ψυρρη
Right here is the right web site for anyone who hopes to find out about this topic. You know a whole lot its almost tough to argue with you (not that I actually will need to…HaHa). You definitely put a new spin on a subject that’s been written about for a long time. Great stuff, just great.
몸캠피싱에 대해 더 알아보니 정말 무서운 일이라는 것을 깨달았습니다. 저희 이 사이트를 둘러보기 에서 안전한 사용 팁을 자세히 확인해보세요
몸캠피싱으로 인한 피해가 심각하다는 것을 알게 되었습니다. 저희 여기서 더 많은 것을 발견하십시오 에서 제공하는 안전한 사용 팁을 참고하세요
Great job! Discover more at pedicure San Antonio
Me ha gustado mucho este artículo sobre los roles y responsabilidades clave en un bufete de abogados práctica legal
This was a wonderful guide. Check out nail salon near me for more
Gracias por compartir información tan valiosa acerca de la legalidad de grabar conversaciones privadas. Me ha resultado muy útil https://raindrop.io/forlensjpv/bookmarks-46227221
Estoy muy agradecido con los abogados de este bufete por su dedicación y esfuerzo en mi caso legal Valores fundamentales
That is a very good tip especially to those fresh to the blogosphere. Short but very accurate info… Many thanks for sharing this one. A must read article.
몸캠피싱은 정말 심각한 문제인 것 같아요. 저희 추가 정보 에서는 이와 관련된 최신 정보와 대처 방법을 제공하고 있습니다
동영상유포 피해에 대한 학교 교육이 더욱 강화되어야 한다고 생각합니다. 도움이 되는 자원 을(를) 통해 이런 제안이 이뤄질 수 있도록 지지하고 싶어요
Fantastic post! Discover more at https://www.giantbomb.com/profile/jarlonojxd/
Me encanta cómo describen los diferentes roles en un bufete de abogados. Es fascinante ver cómo todos contribuyen al éxito del equipo Echa un vistazo al sitio web aquí
Como alguien que necesita encontrar al mejor abogado para su caso, agradezco mucho estos consejos representación legal
There is certainly a lot to know about this issue. I love all the points you’ve made.
Thank you for providing such valuable tips and insights about planning a successful classic desert safari trip morning desert safari dubai
영상유포 피해로부터 안전하게 보호받을 수 있는 방법을 알려드립니다 이 사이트를 확인하십시오
홈페이지 를 통해 영상유포 피해에 대한 대처 방법을 자세히 알아보세요
Thanks for the informative post. More at https://touchofpolishnailsspa.com/
Gracias a este bufete de abogados, resolví mi problema legal de manera rápida y eficiente Expansión conservadora
Excelente post, muy útil para aquellos que están considerando una carrera en el campo legal asesoría legal
El sector fotovoltaico es esencial para lograr un futuro sostenible Retorno de inversión
When it comes to maritime shipping, alpha shipping always goes the extra mile to ensure customer satisfaction
This was a great help. Check out http://becketthjbs802.iamarrows.com/the-thrilling-world-of-online-gambling-in-india-top-websites-for-2024 for more
Este artículo me ha ayudado a entender los factores clave que debo considerar al elegir a un abogado para mi caso legalidad
I must thank you for the efforts you have put in penning this blog. I am hoping to view the same high-grade content from you in the future as well. In truth, your creative writing abilities has motivated me to get my own site now 😉
영상유포 피해 예방을 위한 다양한 전략을 소개합니다 도움이 되는 자원
동영상유포 피해로부터의 보호가 필요한데, 더 많은 정보를 얻기 위해 여기를 클릭하십시오 을(를) 통해 해결책을 찾을 수 있을 것 같아요
¡Me encanta tu enfoque! Es importante conocer nuestros derechos al momento de grabar conversaciones privadas Más consejos útiles
Thanks for the useful suggestions. Discover more at iluma play
Estoy muy agradecido por los consejos y recomendaciones que compartes en esta guía sobre cómo elegir el fondo de inversión perfecto para mi negocio en 2024 https://www.hotel-bookmarkings.win/conoce-las-claves-para-evaluar-la-solidez-financiera-y-estabilidad-de-una-entidad-gestora-antes-de-confiarle-tus
I’ve been using alpha shipping for years, and they have always delivered exceptional maritime shipping services
Trust the professionals at Professional Locksmith Near Box Hill to address all of your locksmith and safeguard demands in Box Hill, Melbourne
The thought of camping in traditional Bedouin tents under the starry sky sounds like an unforgettable experience on a classic desert safari desert safari dubai booking
영상유포 피해 예방을 위한 유용한 자료를 추가 정보 에서 찾아보세요
Spot on with this write-up, I honestly feel this web site needs a great deal more attention. I’ll probably be returning to read through more, thanks for the information!
몸캠피싱에 대해 더 알아보니 정말 위험한 사기 수법인 것 같아요. 저희 계속 읽기 에서 제공하는 안전한 사용 팁을 참고하세요
Me encanta cómo el sector fotovoltaico está creciendo rápidamente y me gustaría explorar las soluciones que ofrece Plantas fotovoltaicas para mi hogar
Gracias por compartir estas valiosas recomendaciones. Implementar el teletrabajo correctamente puede marcar la diferencia en la productividad de una empresa Productividad laboral
The extensive network of ports and vessels offered by alpha shipping makes them a top choice for maritime shipping services
Estoy totalmente de acuerdo en que debemos respetar la legalidad al grabar conversaciones privadas. Gracias por recordárnoslo Grabaciones
The next time I read a blog, I hope that it doesn’t disappoint me as much as this one. I mean, Yes, it was my choice to read through, nonetheless I actually thought you’d have something interesting to talk about. All I hear is a bunch of whining about something that you could fix if you weren’t too busy seeking attention.