目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
토토에그와 관련된 사이트 중에서도 이렇게 다양한 정보와 함께 더 읽기 을(를) 제공하는 곳은 정말 유용하네요
토토에그에 대해 궁금한 것들이 있어서 이 사이트를 찾아보았는데, 정말 유용한 정보들이 많이 있네요. 더 많은 정보를 위한 클릭 을(를) 클릭하면 더 자세한 내용을 볼 수 있어요
토토에그를 검색하면서 이 사이트에서 이 웹사이트를 보십시오 을(를) 찾을 수 있다는 것을 알게 돼서 기쁩니다
토토에그를 찾던 중에 이 사이트를 발견했는데, 여기서 웹사이트 방문 링크를 통해 더 많은 정보를 얻을 수 있다니 정말 기대돼요
Flurex Sports’ activewear is suitable for all types of workouts, from high-intensity training to yoga and Pilates. It’s versatile enough to handle any activity fitness wear wholesale New York USA
Helpful suggestions! For more, visit Chaturbate Pinay
토토에그에 대해 잘 몰랐는데, 이 사이트를 통해 많은 것을 배우게 되었습니다. 더 많은 것을 발견하십시오 으로 들어가서 더 다양한 내용을 확인해보세요
토토에그와 관련된 정보를 찾다가 이 사이트에서 더 많은 정보를 찾아보십시오 을(를) 제공한다는 걸 알게 되었어요. 정말 유용하게 사용할 수 있을 것 같아요
영상유포 피해 예방을 위한 유용한 자료를 여기를 클릭하십시오 에서 찾아보세요
I recently faced a car breakdown in Dubai, and car recovery Dubai came to my rescue. Their team was prompt, skilled, and handled the situation with utmost professionalism and care Fulldown recovery dubai
카지노사이트 게임 사이트 중에서도 가장 안전하고 신뢰할 수 있는 곳입니다 더 많은 정보를 위한 클릭
카지노사이트 중에서도 높은 평가를 받는 이 웹사이트로 이동하십시오 에서 행운을 만나보세요
Gracias por estos consejos, son realmente útiles. https://nutriclean.edublogs.org/2024/07/30/de-que-forma-una-alimentacion-equilibrada-optimizacion-tu-inmunidad/
Car troubles can be a nightmare, but with recovery vehicle dubai at your service, you can rest assured knowing expert help is just a call away in the Emirates
İş yerimizin Karel santral ihtiyaçlarında bize her zaman yardımcı olan bir firma bulmak gerçekten büyük avantaj sağlıyor https://www.karelsantralservisi.com/avcilar-karel-santral-servisi/
Thanks for the helpful advice. Discover more at jawa138
Wysyłamy miliony produktów do ludzi na całym świecie i o każdym z tych produktów możemy powiedzieć, że jest czysty, silny i sprawdzony… Podróżujemy po całym świecie, żeby kontrolować naszych dostawców krem do rąk
I appreciate that kiss_shy chaturbate offers a variety of payment plans, including monthly subscriptions, for those who prefer a more budget-friendly option
Gain a competitive edge in sports betting with the help of AI chatbots. Visit Enhanced Athlete AI Solutions today and unlock a whole new world of gaming possibilities
Cannabis is usually a efficient tool in coping with symptoms of Crohn’s sickness and other gastrointestinal disorders. Learn greater approximately its potential merits at autoflower seed bank
Flurex Sports’ commitment to using sustainable manufacturing processes for their activewear sets them apart from other brands in the industry activewear clothing manufacturers New York USA
Siempre y en todo momento supe que el atún era saludable, pero esto es aún mejor de lo que pensaba. Haga clic para obtener información
몸캠피싱으로부터 안전하게 지키기 위한 방법을 알려주셔서 감사합니다. 저희 도움이 되는 힌트 에서도 더 많은 정보를 제공하고 있어요
The real-time notifications feature on cam lock coupling ensures that you never miss an exciting conversation or connection opportunity
온라인카지노사이트추천에서는 최고의 카지노를 추천해드립니다 더 많은 정보를 얻을 수 있습니다
Clearly presented. Discover more at https://www.spreaker.com/podcast/lainefcuy–6246648
Więcej informacji w naszych Zasadach korzystania z plików cookie. Oznacza to, że za każdym razem, gdy odwiedzasz tę stronę, musisz ponownie włączyć lub wyłączyć ciasteczka everflex nature’s sunshine products
카지노사이트 추천으로 유명한 계속 읽기 에서 엄선된 게임을 즐겨보세요
I stumbled upon this blog while searching for reliable car recovery services in Emirates roadside assistance dubai
몸캠피싱은 사람들이 경계하지 않으면 큰 피해를 입을 수 있는 사기 수법입니다. 저희 여기에서 배우십시오 에서는 이를 예방하기 위한 방법을 제시하고 있어요
Flurex Sports’ activewear range is designed with athletes in mind, ensuring maximum comfort, flexibility, and support during intense workouts workout clothes manufacturer New York USA
몸캠피싱 피해를 예방하기 위해 저희 이 포스트를 바로 여기에서 확인하십시오 에서는 다양한 대처 방법을 안내하고 있습니다
Don’t settle for mediocre when you can have the best – choose granny live sex cams for your Chaturbate needs
Well explained. Discover more at chatruletka-18.com
I am pleased, I have to state. Really not often will i come across your blog which is every educative as well as enjoyable, and let me tell you, you have got strike the actual toenail about the head. The idea will be exceptional; the difficulty is something that doesn’t sufficient folks are speaking wisely about. I am extremely comfortable which i stumbled all through this kind of in my search for a very important factor relating to this.
몸캠피싱은 정말 미묘한 수법으로 사람들을 속이는군요. 저희 이 링크를 따라가기 에서는 이와 관련된 유용한 정보를 제공하고 있습니다
몸캠피싱은 정말 심각한 문제인 것 같아요. 저희 이 포스트를 바로 여기에서 확인하십시오 에서는 이와 관련된 최신 정보와 대처 방법을 안내해드리고 있습니다
##카지노사이트##에서는 어떤 게임을 하면 보다 많은 보너스 혜택을 받을 수 있는지 궁금해요 더 많은 정보를 찾기 위해 클릭하십시오
Appreciate the comprehensive insights. For more, visit spy cam women nude
This is very insightful. Check out 더 많은 정보 for more
동영상유포 피해 예방을 위한 교육이 가장 중요하다고 생각합니다. 더 많은 정보를 위해 여기를 클릭하십시오 을(를) 통해 이런 교육 프로그램에 참여할 수 있는 방법을 알고 싶어요
Whether it’s yoga, running, or weightlifting, Flurex Sports has the perfect activewear for every activity sportswear clothing manufacturer New York USA
Emirates car recovery service stands out from the rest. Their attention to detail and customer satisfaction sets them apart in the industry recovery vehicle dubai
Nicely done! Discover more at https://hackerone.com/lundurryyp33
I’ve been looking for ways to improve my vision without resorting to surgery or medication. This post provides excellent natural remedies. Don’t forget to visit Sight Care eye care expertise for further guidance on achieving 20/20 vision
동영상유포 피해로부터의 보호를 위해서는 법적인 지원도 필요합니다. 이 사이트로 이동하십시오 을(를) 통해 이런 법적인 지원을 받을 수 있는 방법을 알려주세요
영상유포 피해로부터 안전하게 보호되는 방법과 관련된 정보입니다 여기로 엿보기
Flurex Sports’ activewear collection offers a wide range of styles, from classic to trendy, catering to diverse preferences and tastes wholesale gym clothes New York USA
몸캠피싱은 정말 위험한 사기 수법인 것 같아요. 저희 좋은 사이트 에서는 이를 예방하기 위한 다양한 방법을 소개하고 있습니다
카지노사이트 추천으로 유명한 웹사이트로 이동하십시오 에서 엄선된 게임을 즐겨보세요