C 使用叉()生成2个孩子
C++ using fork() to generate 2 children
您是否请检查我的代码,这是一个生成一个父母的孩子的C 程序。用户应输入数值以创建一个过程链。问题是孩子们对每个父母的pid是相同的,我该如何使他们与众不同?
#include<iostream>
#include<sys/types.h>
#include<unistd.h>
#include <sys/wait.h>
using namespace std;
int main()
{
cout<<"Please enter a number of process "<<endl;
int num;
cin>>num;
int j;
for(j=0; j<num; j++)
{
pid_t pid;
pid = fork();
if(pid < 0)
{
cout<<"Error"<<endl;
exit(1);
} else if (pid > 0) {
cout << "Parent " << getpid() << endl;
exit(0);
}
else {
int i;
for(i = 0; i < 2; i++) {
wait(NULL);
cout << " Child " << getpid() << endl;
}
}
}
return 0;
}
输出为
Parent 27130
Child 27322
Child 27322
Parent 27322
Child 31901
Child 31901
Parent 31901
Child 20453
Child 20453
基于托尼·塔尼斯(Tony Tannous)的评论,这是我认为您需要的:
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
void childFun()
{
int i;
for(i = 0; i < 2; i++) {
cout << " Child " << getpid() << endl;
}
}
int main(){
cout<<"Please enter a number of process "<<endl;
int num;
cin>>num;
int j;
for(j=0; j<num; j++)
{
pid_t pid = fork();
if(pid < 0) {
cout<<"Error"<<endl;
exit(1);
} else if (pid > 0) {
cout << "Parent " << getpid() << endl;
// Continue on to create next child.
// Don't exit.
// exit(0);
} else {
// Do whatever the child needs to do.
childFun();
// Exit the child process after that
exit(0);
}
}
return 0;
}
您的代码多个问题。
在else
中,这是子过程。当此过程没有子进程时,您是waiting
...因此,它只会跳过它并将其PID打印两次!。
这与fork
无关,而与您的循环无关。for(i = 0; i < 2; i++)
编辑
如果您只想打印一次,只需删除for循环,它将仅打印一次。
如果您只希望父母两个叉子两个子进程,那么流应该如下:
pid_t pid2;
cout << "Parent " << getpid() << endl;
pid_t pid = fork();
if (pid == -1) { // handle error }
else if (pid == 0) { // child process
cout << " Child " << getpid() << endl;
}
else { // parent process
pid2 = fork();
if (pid2 == -1) { //handle error }
else if (pid2 == 0) { //child process
cout << " Child " << getpid() << endl;
}
相关文章:
- boost::asio如何生成多个协同程序,然后加入它们
- 在C++中随机生成 20 个非重复数字
- 如何通过std::thread生成多个线程
- Qt-grabtoimage()和scale生成两个重叠的图像
- 如何在解决方案中生成多个项目之前执行流程
- 代码在编译时生成三个错误
- cmake 生成多个 compile_commands.json?
- 如何在C++中生成 4 个不同的随机数
- 使用Mersenne-Twister生成多个随机值
- 如何创建一个在C++中生成 3 个掷骰子的函数
- 如何生成多个随机数?
- 问:以下代码将生成多少个类
- C 使用叉()生成2个孩子
- OpenCV源与CUDA编译生成多个定义链接错误
- 使用C randint生成四个数字
- C++生成多个随机数而不循环
- 如何使用Mersenne Twister生成两个数字之间的所有值一次
- c++ 编译器优化是否可以针对布尔参数生成两个版本的函数
- 如何在C 中生成4个不同的数字随机数
- 本应生成 2 个介于 1 和 9 之间的随机数的程序C++只生成 6 和 9 并且没有正确循环