多个孩子的pid脱离了同一个父母
PID of multiple children forked off the same parent
,所以我拥有此主要功能:
int main() {
cout << "Before fork: " << getpid() << endl;
pid_t pid;
pid = fork();
for (int i = 0; i < 3; ++i) {
if (pid < 0) {
cout << "ERROR: Unable to fork.n";
return 1;
}
else if (pid == 0) {
switch(i) {
case 0:
for (int b = 0; b < 10; ++b) {
cout << "b " << getpid() << endl;
cout.flush();
}
break;
case 1:
for (int c = 0; c < 10; ++c) {
cout << "c " << getpid() <<endl;
cout.flush();
}
break;
case 2:
for (int d = 0; d < 10; ++d) {
cout << "d " << getpid() << endl;
cout.flush();
}
break;
default:
cout << "ERROR" << endl;
return 1;
}
}
else {
for (int a = 0; a < 10; ++a) {
cout << "a " << getpid() << endl;
cout.flush();
}
}
}
return 0;
}
该程序的要点同时运行四个过程,每个过程都会在一定次数上打印一个字符。每当我运行该程序时,我都会发现我生了所有的孩子都有相同的pid。应该这样吗?如果不是/,为什么?
您只创建了一个孩子,然后运行一个循环,在该循环中检查它实际上是孩子。要创建三个孩子,您需要三个拨打fork
的电话。即类似的东西:
if ((pid1 = fork()) == 0) {
// work for first child
exit(0);
}
if ((pid2 = fork()) == 0) {
// work for second child
exit(0);
}
if ((pid3 = fork()) == 0) {
// work for third child
exit(0);
}
// work for parent, then:
wait(pid1);
wait(pid2);
wait(pid3);
相关文章:
- 为什么std::async使用同一个线程运行函数
- 多个"常量引用"变量可以共享同一个内存吗?
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 为什么同一个变量的内存地址不同?
- 两个进程可以通过跟踪附加到同一个 PID 吗?
- 如何在同一个 CMAKE 项目中强制链接到共享库?
- 是否可以在文本文件中找到最长单词的长度,并在同一个文本文件中读取,只需 1 个 while 循环?
- 是否可以使用非常量指针调用非常量函数,以及当两个unique_ptrs指向同一个对象时程序的行为方式?
- 不同C++文件中未命名命名空间中的名称可以引用同一个命名事物吗?
- 我应该如何使用 epoll 从同一个 FD 读取和写入
- cuda:多个线程访问同一个全局变量
- 两个抽象类,派生自同一个基类.如何访问从一个抽象类到另一个抽象类的指针
- 如何将不同的函数签名映射到同一个 std::map?
- 多个线程可以读取同一个类成员变量吗?
- 如果我使用同一个密钥推送用户数据两次,会发生什么
- c++同一个键的多个键/值对
- TypeA和TypeB是同一个主类型的别名,如何在C++模板中将它们推导为不同的类型
- 同一个程序每次返回不同的输出
- 为什么同一个逻辑方程在python和c++中返回两个不同的结果
- 多个孩子的pid脱离了同一个父母