如何解决父母与6个孩子之间的命名管道
我想编写一个程序,该程序的父母有6个孩子,每个孩子都有一个id。 (0-maxchild-1) 首先,父级将最后一个子代ID -1(maxchild-1)放入管道中,然后,每个子代都应检查管道中的数字是否等于其ID,并且等于还是非零。 :孩子应该将管道中的数字-1(pipevalue-1)放入管道中,直到管道中的数字达到零为止。如果子级从管道读取的管道值为零,则子级应再次置零并使其完成。
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#define MAXCHILD 6
#define MAXIMUM 100
struct child_proc
{
pid_t pid;
int id;
};
int main()
{
int inChild=0;
int pipe,flag=0;
char path[30];
char buffer[256];
bzero(buffer,256);
struct child_proc child_array[MAXCHILD];
sprintf(path,"1.pipe");
mkfifo(path,0777);
for (int i=0;i<MAXCHILD;i++)
{
int r =fork();
if(r==0){
child_array[i].pid = getpid();
child_array[i].id = i;
inChild=1;
break;
}
/*if(r>0)
{
if(flag == 0) // run only once
{
pipe=open(path,O_WRONLY);
sprintf(buffer,"%d",MAXCHILD - 1);
write(pipe,buffer,strlen(buffer));
flag ++;
//sleep(15);
}
}*/
}
while (inChild==1)
{ // in child
for(int j=0; j<MAXCHILD; j++)
{
if(getpid() == child_array[j].pid)
{
printf("Child id %d starts\n",child_array[j].id);
pipe=open(path,O_RDONLY|O_NONBLOCK);
read(pipe,255);
printf("child id %d pipevalue %d\n",child_array[j].id,atoi(buffer));
pipe=open(path,O_WRONLY);
if(atoi(buffer) == child_array[j].id)
{
//bzero(buffer,256);
sprintf(buffer,child_array[j].id - 1);
printf("child -> %s\n",buffer);
write(pipe,strlen(buffer));
sleep(1);
}
else if(atoi(buffer)==0)
{
//bzero(buffer,256);
sprintf(buffer,0);
write(pipe,strlen(buffer));
printf("Child id %d reach the point\n",child_array[j].id);
exit(0);
}
}
}
}
pipe=open(path,O_WRONLY);
while(inChild==0)
{ // in parent
printf("parent id is: %d\n",getpid());
if(flag == 0) // run only once
{
sprintf(buffer,MAXCHILD - 1);
printf("parent -> %s\n",buffer);
write(pipe,strlen(buffer));
flag ++;
sleep(15);
}
}
return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。