zoukankan      html  css  js  c++  java
  • 共享内存:全双工匿名管道

    //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)


  • 相关阅读:
    [ios]blocks
    [算法] 堆,栈 【转】
    [ios]关于内存错误调试
    [ios]get,post请求 【转】
    [ios]iOS模拟器应用程序目录结构
    [ios]iPhone地图应用开发以及自定义Annotation [转]
    [算法]插入排序
    [ios]让alertView 自动消失【转】
    [ios]延迟执行方法,取消执行方法
    [算法] 基数排序
  • 原文地址:https://www.cnblogs.com/clnchanpin/p/6915325.html
Copyright © 2011-2022 走看看