C++ fork()——创建 "list"进程

标签 c++ fork

我有一个程序可以“一个一个”地创建新进程。是否可以更改此代码以创建一个进程“列表”——即子 1 是子 2 的父,子 2 是子 3 的父,等等?

#include <string>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include "err.h"

using namespace std;
int main ()
{
 pid_t pid;
 int i;

 cout << "My process id = " << getpid() << endl;

 for (i = 1; i <= 4; i++)
  switch ( pid = fork() ) {
  case -1:
    syserr("Error in fork");

  case 0:
    cout << "Child process: My process id = " << getpid() << endl;
    cout << "Child process: Value returned by fork() = " << pid << endl;
    return 0;

  default:
    cout << "Parent process. My process id = " << getpid() << endl;
    cout << "Parent process. Value returned by fork() = " << pid << endl;

   if (wait(NULL) == -1) 
   syserr("Error in wait");

 }  
 return 0;
 }

最佳答案

如果你想保持循环以便动态设置fork树的深度,

// Set DEPTH to desired value

#define DEPTH 4

int main ()
{
  pid_t pid;
  int i;

  cout << "My process id = " << getpid() << endl;

  for (i=1 ; i <= DEPTH ; i++) {

    pid = fork();    // Fork

    if ( pid ) {
       break;        // Don't give the parent a chance to fork again
    }
    cout << "Child #" << getpid() << endl; // Child can keep going and fork once
  }

  wait(NULL);        // Don't let a parent ending first end the tree below
  return 0;
}

输出

My process id = 6596
Child #6597
Child #6598
Child #6599
Child #6600

关于C++ fork()——创建 "list"进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16890546/

相关文章:

grails - Grails日志记录在 fork 模式下不起作用

c - 在 C 中共享子项和父项之间的链表

C++ GetAsyncKeyState 和 GetCursorPos 与 Windows 消息传递

c++ - 确保用户只输入两个词之一

c - 将子进程的返回值接收到父进程中?

c - 无法从子进程内部将数据写入文件

c - C 中 "On demand"服务器中的共享内存结构

c++ - 通过Boost Fusion获得结构名称

c++ - MySQL C++ 连接器程序抛出错误 15

c++ - Qt5 和 Cmake 链接 QApplication 头错误