[英]fork mulitple child in one parent
我想在一個父進程中派生三個子進程。 以下是我的C ++代碼:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
using namespace std;
int main()
{
pid_t pid;
for (int i = 0; i < 3; i++)
{
pid = fork();
if (pid < 0)
{
cout << "Fork Error";
return -1;
}
else if (pid == 0)
cout << "Child " << getpid() << endl;
else
{
wait(NULL);
cout << "Parent " << getpid() << endl;
return 0;
}
}
}
現在我的輸出是:
Child 27463
Child 27464
Child 27465
Parent 27464
Parent 27463
Parent 27462
我應該如何修改程序以獲取如下所示的輸出?
Child 27463
Child 27464
Child 27465
Parent 27462
我的意思是這三個孩子需要屬於同一個父母,有人可以給我一些建議嗎?
謝謝你們。 :)
您應該退出子進程的執行。 否則,他們也會繼續分叉
pid_t pid;
for(i = 0; i < 3; i++) {
pid = fork();
if(pid < 0) {
printf("Error");
exit(1);
} else if (pid == 0) {
cout << "Child " << getpid() << endl;
exit(0);
} else {
wait(NULL);
cout << "Parent " << getpid() << endl;
}
}
有兩個問題:
for
循環,從而產生進一步的過程; 以下將產生您想要的輸出:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
using namespace std;
int main()
{
pid_t pid;
for (int i = 0; i < 3; i++)
{
pid = fork();
if (pid < 0)
{
cout << "Fork Error";
return -1;
}
else if (pid == 0) {
cout << "Child " << getpid() << endl;
return 0;
} else {
wait(NULL);
if (i == 2) {
cout << "Parent " << getpid() << endl;
}
}
}
}
當我運行它時,我得到
Child 4490
Child 4491
Child 4492
Parent 4489
將return 0
從最后一個條件移到中間一個條件:
if (pid < 0)
{
cout << "Fork Error";
return -1;
}
else if (pid == 0) {
cout << "Child " << getpid() << endl;
return 0;
}
else
{
wait(NULL);
cout << "Parent " << getpid() << endl;
}
這樣,父級將繼續循環,而子級將終止而不是循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.