unix網絡編程卷二——進程間通信

一、簡介

第一章 簡介

1.1 概述

 

1.2 進程、線程與信息共享

 

 

1.3 IPC對象的持續性

 

 

 

1.4 名字空間

 

 

1.5 fork、exec、exit對IPC對象的影響

 

 

 

第二章 Posix IPC

2.1 概述

 

 

2.2 IPC名字

 

 

px_ipc_name函數

 

 

2.3 創建與打開IPC通道

 

 

小結

 

 

 

第三章 system v ipc

 

 


第二部分 消息傳遞

第四章 管道和FIFO

4.1 概述

 

 

4.2 管道

 

 

 

兩個管道的客戶端-服務器程序

#include"unpipc.h"

void client(int, int), server(int, int);

int main(int argc, char**argv){
    int pipe1[2], pipe2[2];
    pid_t childpid;
    Pipe(pipe1);
    Pipe(pipe2);

    if((childpid = Fork()) == 0){ //child
        Close(pipe1[1]);
        Close(pipe2[0]);

        server(pipe1[0], pipe2[1]);
        exit(0);

    }

    Close(pipe1[0]);
    Close(pipe2[1]);

    client(pipe2[0], pipe1[1]);
    Waitpid(childpid, NULL,0);
    exit(0);
}

void client(int readfd, int writefd){
    size_t len;
    ssize_t n;
    char buff[MAXLINE];

    //從標準輸入讀取路徑名
    Fgets(buff, MAXLINE, stdin);
    len = strlen(buff);  //fgets guarantees null byte at end
    if(buff[len-1] == '\n'){
        len--;           //delete newline frim fgets
    }

    Write(writefd, buff, len);
    while((n=Read(readfd, buff, MAXLINE))>0)
        Write(STDOUT_FILENO, buff, n);

}

void server(int readfd, int writefd){
    int fd;
    ssize_t n;
    char buff[MAXLINE+1];

    //read pathname from IPC channel 
    if((n=Read(readfd, buff, MAXLINE))==0)
        err_quit("END OF FILE WHILR READING PATH");
    buff[n] = '\0'; //null terminate pathname

    if((fd =open(buff, O_RDONLY))<0){
        snprintf(buff+n, sizeof(buff)-n, "cannot open, %s\n",
            strerror(errno));
        n = strlen(buff);
        Write(writefd, buff, n);
    }else{
        while((n=Read(fd, buff, MAXLINE))>0)
            Write(writefd, buff, n);
        Close(fd);
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

未完待續

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章