pipe - How does the parent select which forked child process to communicate with? -
i created several kid processes 1 parent, , created bidirectional pipes between each process , parent. problem how can go , forth between kid processes , parent different type of works, , allow children communicate parent? thinking maintain track of each process's pid, , utilize identity switch. technically, how? attached code have far.
struct val { int testint; char testchar; }; int main () { val val1; pid_t cpid[3]; int fd[2], fdd[2]; int sfc; (int i=0; i<3; i++) { pipe(fd); pipe(fdd); cpid[i]=fork(); if(cpid[i]==0) { cout<<"\ni kid , pid is:"<<getpid(); cout<<"\nmy parent is: "<<getppid(); sfc=i; close(fd[1]);//close fd-pipe write end kid read(fd[0], &val1, sizeof(val1));//read pipe close(fdd[0]); write(fdd[1], &sfc, sizeof(sfc)); close(fd[0]); close(fdd[1]); cout<<"\nchild received value: "<<val1.testint<<val1.testchar; cout<<"\nchild sent value: "<<sfc; cout<<endl; break; } else { close(fd[0]);//parent close read end of pipe fd close(fdd[1]);//parent close write end of pipe fdd val1.testint=4; val1.testchar='a'; write(fd[1], &val1, sizeof(val1));//parent write fd read(fdd[0], &sfc, sizeof(sfc));//parent read fdd close(fd[1]); close(fdd[0]); wait(null); cout<<"\ni parent , have child: "<<cpid[i]; cout<<"\nparent sent out value: "<<val1.testint<<val1.testchar; cout<<"\nparent received value: "<<sfc<<endl; } } homecoming 0;
}
process pipe fork
No comments:
Post a Comment