pipe用來創(chuàng)建管道,但是單個管道只能單向通信,一端用于讀,而另一端用于寫。如果要實現(xiàn)進程雙向通信,必須創(chuàng)建一對管道。具體實現(xiàn)忽略。而socketpair則可以用來創(chuàng)建雙向通信的管道。取決于底層實現(xiàn),打開的還是一個文件,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

#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;運行截圖:

另外有需要云服務器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內外云服務器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務器、裸金屬服務器、高防服務器、香港服務器、美國服務器、虛擬主機、免備案服務器”等云主機租用服務以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應用場景需求。
網(wǎng)頁名稱:socketpair實現(xiàn)進程通信-創(chuàng)新互聯(lián)
本文路徑:http://www.chinadenli.net/article4/dhdeoe.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供全網(wǎng)營銷推廣、搜索引擎優(yōu)化、虛擬主機、App開發(fā)、網(wǎng)站制作、網(wǎng)站設計
聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)