目录
问题
- 有的时候,程序运行后的输出结果会在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()返回值不同,两者可以依据分支语句区分,然后后续执行不同的代码
Профессиональный сервисный центр по ремонту бытовой техники с выездом на дом.
Мы предлагаем:сервисные центры по ремонту техники в екб
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
Профессиональный сервисный центр по ремонту варочных панелей и индукционных плит.
Мы предлагаем: профессиональный ремонт варочных панелей
Наши мастера оперативно устранят неисправности вашего устройства в сервисе или с выездом на дом!
“Is it true that some companies provide complimentary champagne on certain tours? That would be perfect when booking through helicopter tours dubai
슬롯사이트추천으로 다양한 슬롯 사이트를 이용해보세요 더 많은 정보를 찾아보십시오
Wer hat noch nicht von den besten Geheimtipps für Unterkünfte gehört? Entdeckt sie hier: https://www.demilked.com/author/campingplatzspreewaldstadtetripbesuchensya/
온라인슬롯 추천으로 유명한 이곳에서 다양한 슬롯 게임을 즐길 수 있으며, 잭팟도 기대할 수 있습니다 원본 출처
I love how helicopter tours give you a unique perspective of the city helicopter packages Dubai 12 minutes
“I love how every corner of Dubai has something unique to offer; can’t wait to discover them all from above via %% anyKeyWord %% helicopter sightseeing tours Dubai
Valuable information! Discover more at 읽기에 좋은 게시물
영상유포 피해로부터 안전하게 보호받을 수 있는 방법을 알려드립니다 웹사이트로 이동하십시오
이 링크 방문 을(를) 통해 토토사이트에 가입하고 베팅을 시작했는데, 빠른 정산과 안정적인 결제 시스템으로 매번 만족하고 있어요
Appreciate the insightful article. Find more at 여기서 더 많은 것을 발견하십시오
Great insights! Find more at kostenloser Video-Chat
The significance of each design in these idols brings so much meaning to our celebrations—visit Ganpati Murti for Vinayaka Chavithi from Moolwan
Hier sind einige der besten Tipps für die Suche nach einer passenden Unterkunft: schau bei https://500px.com/p/schlosshotelmritzurlaubverwhneneeyy
This was quite useful. For more, visit Look at more info
The Significance of Oscillation Mitigation Systems in Industrial Equipment
In industrial settings, devices along with turning equipment serve as the core of operations. Yet, a of the commonly frequent problems that can obstruct its efficiency along with lifetime remains oscillation. Oscillation might bring about a range of complications, including minimized exactness as well as efficiency resulting in increased wear and tear, ultimately causing costly downtime and restoration. This is the point where resonance control equipment is necessary.
Why Oscillation Control is Critical
Vibration in equipment can bring about multiple harmful outcomes:
Minimized Functional Efficiency: Exaggerated vibrations might bring about discrepancies and distortion, decreasing total efficiency in the devices. This might result in reduced production times and higher energy consumption.
Greater Deterioration: Constant vibration speeds up the erosion of machinery parts, resulting in more frequent upkeep and the chance of unexpected unforeseen malfunctions. Such a situation does not just increases operating costs and shortens the durability of the equipment.
Protection Dangers: Unmanaged vibration could introduce considerable safety concerns both to both the equipment and the machines and the personnel. In severe cases, extreme situations, it might cause disastrous machinery failure, threatening workers as well as resulting in considerable devastation across the site.
Accuracy and Quality Problems: In businesses that demand high accuracy, for example industrial sectors or space industry, oscillations may cause errors during production, resulting in faulty goods and increased waste.
Reasonably Priced Solutions towards Oscillation Control
Investing in vibration control equipment proves not just necessary and a wise choice for any business involved with equipment. The offered modern vibration mitigation tools are designed to intended to remove vibrations from all machine or spinning equipment, providing uninterrupted as well as efficient functioning.
What sets these systems from others is its reasonable pricing. We understand the necessity of cost-effectiveness within the modern competitive marketplace, which is why we offer high-quality vibration management solutions at costs that won’t break the bank.
Through selecting our systems, you aren’t simply securing your machinery and boosting its efficiency as well as investing towards the long-term achievement of your business.
Conclusion
Vibration control is an essential aspect in ensuring the effectiveness, safety, and lifetime of your equipment. With our economical resonance mitigation apparatus, one can ensure your production operate seamlessly, all goods maintain high quality, as well as all personnel stay safe. Don’t let oscillation compromise your business—invest in the appropriate systems today.
Kan någon rekommendera en familjevänlig t Kosmetisk tandvård Göteborg
Thanks for the informative content. More at https://medium.com/@laurentaylor549/best-champion-wide-leg-sweatpants-f3611a994b32
Wer von euch hat Tipps für besondere Unterkünfte? Ich kann nur sagen https://www.instapaper.com/read/1706615322
This was very insightful. Check out kostenloser Video-Chat for more
Thanks for the useful post. More like this at https://gist.github.com/bestsoftwaretopappreviews33
This was very well put together. Discover more at https://jacksoncook3.medium.com/
Если вы искали где отремонтировать сломаную технику, обратите внимание – профи услуги
вавада|vavada|вавада казино|вавада зеркало|vavada зеркало|vavada casino|vavada казино|казино вавада|вавада рабочее зеркало|вавада официальный сайт|vavada регистрация|vavada официальный сайт|вавада регистрация|вавада вход|vavada рабочее зеркало|вавада https://nexxpro.biz/
Ho provato vari siti, ma il tuo offre la migliore selezione di ##semi cannabis femminizzati## a prezzi competitivi http://jaredxtfc169.trexgame.net/consigli-pratici-per-coltivare-semi-femminizzati-indoor-senza-problemi
Les graines autofloraison CBD sont parfaites pour les cultivateurs qui veulent obtenir rapidement une récolte riche en CBD sans avoir à se soucier des cycles de lumière. Je suis reconnaissant d’avoir découvert meilleur graine autofloraison extérieur
If you are seeking authentic providers of Amnesia Haze seeds, cannabis seeds is your move-to destination for utmost excellent and delight
Hello guys , keep up the good work Get more info
Thanks for the informative post. More at https://orchidnailbarsalon.com/
Great insights! Find more at https://medium.com/@hoffertalisha3/list/reading-list
Thanks for the great explanation. More info at https://medium.com/@bevi.sina1973/elevate-your-dining-experience-the-top-11-birch-dining-tables-for-timeless-charm-95690f5fa4c9
온라인카지노사이트추천에서는 사용자 평점이 높은 카지노를 추천해드립니다 웹사이트 보기
вавада|vavada|вавада казино|вавада зеркало|vavada зеркало|vavada casino|vavada казино|казино вавада|вавада рабочее зеркало|вавада официальный сайт|vavada регистрация|vavada официальный сайт|вавада регистрация|вавада вход|vavada рабочее зеркало|вавада https://nexxpro.biz/
저희 정보 게시물 에서는 다양한 게임과 특별한 혜택이 여러분을 기다리고 있습니다
##카지노사이트##에서는 어떤 게임을 하더라도 균등한 기회를 제공해주는지 알려주세요 여기에서 배우십시오
вавада|vavada|вавада казино|вавада зеркало|vavada зеркало|vavada casino|vavada казино|казино вавада|вавада рабочее зеркало|вавада официальный сайт|vavada регистрация|vavada официальный сайт|вавада регистрация|вавада вход|vavada рабочее зеркало|вавада https://nexxpro.biz/
Appreciate the useful tips. For more, visit 정보를 위해 클릭하십시오
카지노사이트추천으로 유명한 이곳에서는 사용자 평점을 확인하면서 좋은 베팅 옵션을 찾을 수 있습니다 이 웹사이트로 이동하십시오