开发者

Multiple read/writes with pipes in C

开发者 https://www.devze.com 2023-02-15 09:10 出处:网络
I\'ve seen lots of examples of pipes that read from a child and write to a parent or vice versa.For example:

I've seen lots of examples of pipes that read from a child and write to a parent or vice versa. For example:

    /* this example shows how unnamed pipes may be u开发者_如何学运维sed */

#include <unistd.h>
#include <stdio.h>
#include <errno.h>

int main() {
int ret_val;
int pfd[2];
char buff[32];
char string1[]="String for pipe I/O";

ret_val = pipe(pfd);                 /* Create pipe */
if (ret_val != 0) {             /* Test for success */
  printf("Unable to create a pipe; errno=%d\n",errno);

  exit(1);                         /* Print error message and exit */
}
if (fork() == 0) {
   /* child program */
   close(pfd[0]); /* close the read end */
   ret_val = write(pfd[1],string1,strlen(string1)); /*Write to pipe*/
   if (ret_val != strlen(string1)) {
      printf("Write did not return expected value\n");
      exit(2);                       /* Print error message and exit */
   }
}
else {
   /* parent program */
   close(pfd[1]); /* close the write end of pipe */
   ret_val = read(pfd[0],buff,strlen(string1)); /* Read from pipe */
   if (ret_val != strlen(string1)) {
      printf("Read did not return expected value\n");
      exit(3);                       /* Print error message and exit */
   }
   printf("parent read %s from the child program\n",buff);

}
exit(0);
}

However, I need to write a string to the child process, then do some string manipulations, then write it back to the parent process. So each parent/child needs to read and write. Problem is synchronization or something, because when I try to read back the manipulated string in the parent process, the child process already ended and so the string is garbage. I'm new to pipes but I've tried sleep() and wait() but to no avail, any suggestions?


You need two (sets of) pipes, one that the parent writes and the child reads and the other that the child writes and the parent reads.

There should be no problem with synchronization, assuming that you correctly handle the possibility that write will not write the entire string and that you correctly close the written fd before exiting the child.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号