您好,登錄后才能下訂單哦!
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
#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)行截圖:
免責(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)容。