父子进程间通信实例(bully实现碰到的问题)

/* bully_al.h */
/*
bully algorithm */#define MAXHOST 100 #define INITHOST 2 #define random(x) (rand()%x) /* 主进程中存所有host的ID */ map<int,int> AllID;/* <hostID, pid> */ vector<string>::iterator it_v; /* 主机 */ class Hosts{ public: int hostID;/* ID */ pid_t pid = -1;/* 进程id */ int leaderID; int isLeader = 0; map<int,int> OthersID;/* <hostID, pid> */ Hosts(); ~Hosts(); }; Hosts::Hosts(void){ ; } Hosts::~Hosts(void){ ; } /* 选举消息 0 存活消息 1 胜利消息 2 heartbeat message 3 */ /* 消息格式 */ /* "msgtype:srcID:dstID:pid" */ /* 1、初始化所有子进程,给OthersID赋值 2、进程间通信 3、流程 */

bully实现流程:
一、准备部分

  利用子进程模拟host:主进程先fork N个子进程,child马上exec执行主机模拟代码,每个child随机分配一个0-65535的hostID,并由子进程讲pid-hostID返回给父进程(使用pipe)

  所有child fork完之后,用AllID更新所有的子进程内存中的OthersID(使用消息队列)

如何让映像进程获取管道数据:

  子进程调用exec函数后,开始执行一段新的代码,此时已经替换了当前进程的正文、数据、堆栈。

exec后的程序均不会被执行。

1 execl("./hostexe","hostexe",NULL);

法一:将管道的fd作为exec参数传递给hostexe

/*fd[1]读管道*/
char writefd[10];
sprintf(fd,"%d",fd[1]);
execl("./hostexe","hostexe",writefd,NULL)


/*execl code*/
cout << argv[1] << endl;

法二:dup2()将管道的fd复制成hostexe的标准输入

猜你喜欢

转载自www.cnblogs.com/threewater/p/10972104.html