socketpair实现进程通信

发布时间:2020-07-23 06:55:50 作者:小止1995
来源:网络 阅读:1016

pipe用来创建管道,但是单个管道只能单向通信,一端用于读,而另一端用于写。如果要实现进程双向通信,必须创建一对管道。具体实现忽略。而socketpair则可以用来创建双向通信的管道。取决于底层实现,打开的还是一个文件,fd[0],fd[1],管道中f[0]读端,f[1]写端。

#include <sys/types.h>   

#include <sys/socket.h>

int socketpair(int domain, int type, int protocol, int sv[2]);

domain:选用AF_LOCAL;

type:SOCK_STREAM

protocol:默认0

socketpair实现进程通信

#include<stdio.h>                                                                      
#include<stdlib.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
int main()
{
    int fd[2];
    if(socketpair(AF_LOCAL,SOCK_STREAM,0,fd)<0){
        perror("sockpair");
        return 1;
    }
    pid_t id=fork();
    if(id<0){
        perror("fork");
        return 2;
    }
    else if(id==0){
        close(fd[0]);
        char buf[1024];
        while(1)
                {
            ssize_t _s;
            strcpy(buf,"hello bit");
            write(fd[1],buf,strlen(buf));
            _s=read(fd[1],buf,sizeof(buf)-1);
            buf[_s]='\0';
            printf("father->child%s\n",buf);
        }
        close(fd[1]);
    }
    else{
        close(fd[1]);
        char buf[1024];
        while(1)
        {
            ssize_t _s=read(fd[0],buf,sizeof(buf)-1);
            if(_s>0){
                buf[_s]='\0';
                printf("child -> father %s\n",buf);
            }
            strcpy(buf,"hello world");
            write(fd[0],buf,strlen(buf));
        }              
        close(fd[0]);
        //wait child
    }
    return 0;

运行截图:

socketpair实现进程通信

推荐阅读:
  1. 高级I/O-----socketpair
  2. 高级IO中socketpair实现进程间通信以及重定向

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

socketpair tpa

上一篇:【短信插件】短信如何对接74cms_v4.2.66_骑士人才系统

下一篇:MS-SQL CLR 直接读写文件,飞一般的感觉!

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》