简体   繁体   中英

communication between parent and child through pipe

I want a program where the parent and child talk each other. so the output would be:

  • p: value
  • c: value
  • p: word
  • c: word

and so on.....

Below there is an example of code where the output makes first talk the parent and after the childs. How can I correct the code?

    for(int i=0; i<N; i++){
            pid=fork();
            if(pid==-1){
                    perror("fork\n");
                    exit(EXIT_FAILURE);
            }
            else if(pid==0){
                    srand(time(NULL));
                    int c;
                    read(fd[i][0], &c, 1);
                    printf("c: value: %d\n", c);
                    char word[c];
                    read(fd[i][0],&word, sizeof(word));
                    printf("c: word: %s\n", word);
                    int sum;
                    sum=c*i;
                    write(fd[i][1], &sum, sizeof(int));
                    printf("c: sended %d\n", sum);
                    int flag=0;
                    printf("flag :%d\n", flag);
                    read(fd[i][0], &flag, sizeof(int));
                    printf("c: flag= %d ->exit\n", flag);
                    exit(1);
            }else{
                    int c;
                    c=rand()%100+1;
                    write(fd[i][1], &c, sizeof(int));
                    printf("p: value: %d\n", c);
                    char word[c];
                    write(fd[i][1], &word, sizeof(word));
                    printf("p: word: %s\n", word);
                    int sum;
                    read(fd[i][0], &sum, sizeof(int));
                    printf("p: sum is: %d\n", sum);
                    int flag=1;
                    write(fd[i][1], &flag, sizeof(int));
                    printf("par: flag exit %d\n", flag);
                    wait(NULL);
            }
    }

To have duplex communication between two processes, you need two<\/em> pipes:

  1. <\/li>
  2. <\/li><\/ol>

    If you use the same pipe for both, then you can end up with a situation like the child writing something to the pipe, and directly read it back again (and the parent will never see the data).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM