c中的双向任意管道

时间:2015-05-20 18:42:30

标签: c pipe posix

我已经用Ubuntu在C中编写了这个(希望是正确的)匿名管道,但是我无法在两个方向上连接。我怎样才能以最简单的方式解决这个问题,从孩子到父母以及从父母到孩子的连接?

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

ret_val = pipe(pfd);   

if (fork() == 0) {
   // child 
   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
   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);
}

1 个答案:

答案 0 :(得分:0)

见下文,它只是这样工作,因为管道缓冲4KB,字符串较小,否则可能会陷入死锁。

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

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

    ret_val = pipe(pfd), pipe(dfp);

    pid_t pid = fork();
    if (0 > pid) {
        printf("Error forking\n");
        exit(1);
    }
    if (pid == 0) {
        // child
        close(pfd[0]); // close the read end
        close(dfp[1]); // close the write 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
        }
        ret_val = read(dfp[0],buff,strlen(string2)); /* Read from pipe */
        if (ret_val != strlen(string2)) {
            printf("Read did not return expected value\n");
            exit(3);                       /* Print error message and exit */
        }
        printf("child read '%s' from the parent program\n",buff);
    }
    else {
        // parent
        close(pfd[1]); /* close the write end of pipe */
        close(dfp[0]); /* close the read end */
        ret_val = write(dfp[1],string2,strlen(string2)); /*Write to pipe*/
        if (ret_val != strlen(string2)) {
            printf("Write did not return expected value\n");
            exit(2); // Print error message and exit
        }
        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);
        wait(NULL);
    }
    exit(0);
}