溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

socketpair實(shí)現(xiàn)進(jìn)程通信

發(fā)布時(shí)間:2020-07-23 06:55:50 來(lái)源:網(wǎng)絡(luò) 閱讀:1024 作者:小止1995 欄目:編程語(yǔ)言

pipe用來(lái)創(chuàng)建管道,但是單個(gè)管道只能單向通信,一端用于讀,而另一端用于寫(xiě)。如果要實(shí)現(xiàn)進(jìn)程雙向通信,必須創(chuàng)建一對(duì)管道。具體實(shí)現(xiàn)忽略。而socketpair則可以用來(lái)創(chuàng)建雙向通信的管道。取決于底層實(shí)現(xiàn),打開(kāi)的還是一個(gè)文件,fd[0],fd[1],管道中f[0]讀端,f[1]寫(xiě)端。

#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:默認(rèn)0

socketpair實(shí)現(xiàn)進(jìn)程通信

#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;

運(yùn)行截圖:

socketpair實(shí)現(xiàn)進(jìn)程通信

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI