//main.cpp#include#include #include #include 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.outMAINCPP=main.cppMAINO=main.oCC=g++$(OUT):$(MAINO) $(CC) -o $@ $^$(MAINO):$(MAINCPP) $(CC) -c $<.PHONY:cleanclean: rm -rf $(OUT) $(MAINO)