码迷,mamicode.com
首页 > 其他好文 > 详细

共享内存:全双工匿名管道

时间:2017-05-28 11:50:41      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:article   cpp   void   pipe   ==   while   $@   std   for   

//main.cpp
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
using namespace std;
//两个进程共享驻留在内核中的信息。每次訪问共享信息的操作就涉及系统调用。

 void EXIT(int arg) { cout<<"SIGINT "<<"is quit"<<endl; exit(0); } int Write(int fd,const char *buff,int n) { ssize_t count = 0; if((count=write(fd,buff,n))==-1) { cout<<"write error!!!"<<endl; return -1; } return count; } int Read(int fd,char *buff,int n) { ssize_t count = 0; if((count=read(fd,buff,n))==-1) { cout<<"read error!!!"<<endl; return -1; } return count; } int main() { int fd[2],pd[2]; pipe(fd); pipe(pd); signal(SIGINT,EXIT); pid_t id; if((id=fork())==0) { close(fd[0]); close(pd[1]); char buff[255]; memset(buff,0,sizeof(buff)); while(1) { Write(fd[1],"I am child process!",20); Read(pd[0],buff,sizeof(buff)); cout<<buff<<endl; sleep(1); } } else if(id>0) { close(pd[0]); close(fd[1]); char buff[255]; memset(buff,0,sizeof(buff)); while(1) { Read(fd[0],buff,sizeof(buff)); cout<<buff<<endl; Write(pd[1],"hello child",11); } } else { cout<<"fork() error!!"<<endl; } return 0; }

Makefile:

OUT=a.out
MAINCPP=main.cpp
MAINO=main.o
CC=g++

$(OUT):$(MAINO)
	$(CC) -o $@ $^
$(MAINO):$(MAINCPP)
	$(CC) -c $<

.PHONY:clean
clean:
	rm -rf $(OUT) $(MAINO)


共享内存:全双工匿名管道

标签:article   cpp   void   pipe   ==   while   $@   std   for   

原文地址:http://www.cnblogs.com/clnchanpin/p/6915325.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!