全双工管道

来源:互联网 发布:淘宝情趣女模特 编辑:程序博客网 时间:2024/04/28 14:26

管道创建:

int pipe(int fd[]);

fd[0]/fd[1]分别对应:读、写

全双工管道,顾名思义就是数据通讯是双向的,即fd[0]/fd[1]都可用来读或者写

摘录一个小例子(来自Unix Neworking Programming Volume 2 Interprocess communications)

稍改动过:

#include <stdio.h>#include <errno.h>#include <unistd.h>#include <sys/socket.h>#include <sys/types.h>#define MAXLINE 255void error_msg_quit(char *string, int line){    char msg[MAXLINE] = {0};    int len = 0;    sprintf(msg, "%s", string);    len = strlen(string);    snprintf(msg + len, strlen(strerror(errno)), ",line:%d,%s\n", line, strerror(errno));    fputs(msg, stdout);    exit(errno);}int main(int argc, char **argv){    int fd[2], n;    char ch;    pid_t child_pid;    //create pipe    //pipe(fd);    socketpair(AF_UNIX, SOCK_STREAM, 0, fd);//if donot set this option,it won't work properly.    if ((child_pid = fork()) == 0)    {        //child        sleep(3);        if ((n = read(fd[0], &ch, 1)) != 1)        {            error_msg_quit("read error", __LINE__);        }        printf("child read:%c\n", ch);        write(fd[0], "c", 1);        exit(0);    }    //parent    write(fd[1], "p", 1);    if ((n = read(fd[1], &ch, 1)) != 1)    {        error_msg_quit("read error", __LINE__);    }    printf("parent read:%c\n", ch);    exit(0);}

socketpair这个系统调用是后来自己加的,如果不加的话,程序是不太正常的,加了这句话这后,说明这里创建的管道就是全双工的了~或者因为编译平台不同,程序执行结果也会不同吧,书上说利用pipe而没有这里的socketpair函数,可以得到期望的结果,但是在我的fedora上没有出现,solaris上能不能ok我也不知~!