#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
int main()
{
int pfd[2];
int status,i;
char input[1024];
int rfds[n]; //Hold the file IDs of each pipe fd[0]
int wfds[n]; //Holds the file IDs of each pipe fd[1]
int pids[n]; //Holds the list of child process IDs
while(fgets(input,sizeof(input),stdin)){
for (i=0;i<6;i++){
if(pipe(pfd) < 0)
{
printf("Failed to create pipe!\n");
return 1;
}
//Store the pipe ID
rfds[i] = pfd[0];
wfds[i] = pfd[1];
if((pids[i] = fork())<0){
printf("Failed to fork!\n");
return 1;
}
if (pids[i]==0) {
close(wfds[i]);
if(read(rfds[i],input,strlen(input)) > 0)
{
printf("process #%d (%d) relaying message:%s",i,getpid(),input);
}
close(rfds[i]);
}
else
{
close(rfds[i]);
if((write(wfds[i], input, strlen(input))) ==-1)
{
printf("Failed to write!\n");
return 1;
}
close(wfds[i]);
wait(&status);
}
}
}
return 0;
}
我对此进行编码以在进程之间传输消息。但我想让最后一个进程连接到第一个进程。即,它的输出是什么样的
process #0 (47652) sending message: MD
process #1 (47653) relaying message: MD
process #2 (47654) relaying message: MD
process #3 (47655) relaying message: MD
process #4 (47656) relaying message: MD
process #5 (47657) relaying message: MD
process #6 (47658) relaying message: MD
我需要的是最后一个进程在进程 id 47651 而不是 47658 的进程中完成