歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux進程間管道通信

Linux進程間管道通信

日期:2017/3/1 9:11:20   编辑:Linux編程

Linux進程間管道通信

mkfifo()

//創建有名管道(FIFO special file),創建完了就像普通文件一樣open(),再讀寫,成功返回0,失敗返回-1設errno。VS$man 3 mkfifo
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);

pathname:the FIFO special file's name

mode :the FIFO's permissions.

//創建FIFO管道文件
int res=mkfifo(“./a.fifo”,0664);
if(-1==res)
    perror("mkfifo"),exit(-1);
res=open(“./a.fifo”,O_RDONLY);
if(-1==res)
    perror(“open”),exit(-1);

pipe()

//創建無名管道,相當於直接把open()返回的fd直接放到形參中,而不需額外的變量接收管道文件的描述符,用於父子進程間通過管道進行IPC通信,,成功返回0,失敗返回-1設errno
#include <unistd.h>
int pipe(int pipefd[2]);

pipefd :return two fds referring to the ends of the pipe.

  • pipefd[0] :read end,讀端
  • pipefd[1] :write end,讀端.

fork()創建的child也會文件描述符總表也會復制一份So,對於child, 應該先關閉讀端, 再寫,對於parent,應該先關閉寫端, 再讀

//使用pipe()實現父子進程的通信
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<stdio.h>
int main(){
    //1. 創建無名管道
    int pipefd[2];
    int res=pipe(pipefd);
    if(-1==res)
        perror("pipe"),exit(-1);
    //2. 創建子進程
    pid_t pid=fork();
    if(-1==pid)
        perror("fork"),exit(-1);

    //3. 子進程開始啟動,寫入1~100;
    if(0==pid){
        close(pipefd[0]);
        int i=0;
        for(i=1;i<=100;i++){
            write(pipefd[1],&i,sizeof(int));
        }
        close(pipefd[1]);//關閉寫端
        exit(0);
    }
    
    //4. 父進程開始啟動,讀取管道中的數據
    close(pipefd[1]);
    int i=0;
    for(i=1;i<=100;i++){
        int x=0;
        read(pipefd[0],&x,sizeof(int));
        printf("%d ",x);
    }
    printf("\n");
    close(pipefd[0]);
    return 0;
}

Copyright © Linux教程網 All Rights Reserved