全双工管道

44 篇文章 1 订阅
24 篇文章 1 订阅

管道创建:

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 255

void 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我也不知~!





  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值