进程间通信--无名管道(pipe)
生活随笔
收集整理的這篇文章主要介紹了
进程间通信--无名管道(pipe)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
無名管道通信(pipe)
無名管道通信主要用于父子進(jìn)程之間,依賴fork的復(fù)制,或者vfork的共享,得以分享所得的無名管道的文件描述符。
總結(jié)其性質(zhì)有以下幾點
1. 管道是半雙工的,數(shù)據(jù)在一個時間只能向一個方向流動;
2. 需要雙方通信時,習(xí)慣于建立起兩個管道(關(guān)閉一個的讀端和另一個的寫端)
3. 只能用于父子進(jìn)程或者兄弟進(jìn)程之間(具有親緣關(guān)系的進(jìn)程);
4. 通信過程發(fā)生在內(nèi)核中,不依賴于文件系統(tǒng)(文件系統(tǒng)中不存在臨時文件)
5. 寫一次只能讀一次
函數(shù)原型:
#include <unistd.h>int pipe(int pipefd[2]);調(diào)用前int my_pipe[2] 這個用于存放當(dāng)前管道的fd
my_pipe[0]為讀端 my_pipe[1]為寫端
所以在父子進(jìn)程中要關(guān)閉其中的一端,
如父進(jìn)程向子進(jìn)程 那么父進(jìn)程關(guān)閉讀端,子進(jìn)程關(guān)閉寫端。
demo:
#include <unistd.h> #include <stdio.h> #include <errno.h> #include <string.h>#define BUF_SIZE 64int main(int argc, char const *argv[]) {int fd_pipe[2];int ret = -1;const char word[] = {"hello world"};char buf[64];memset(buf, 0, sizeof(buf));pipe(fd_pipe);ret = fork();if(ret < 0){perror("pipe");return -1;}if(0 == ret){printf("%s\n", "in parent process");close(fd_pipe[0]);write(fd_pipe[1], word, sizeof(word));}else{printf("%s\n", "in child process");sleep(1);read(fd_pipe[0], buf, BUF_SIZE);printf("I get :%s\n", buf);close(fd_pipe[1]);}return 0; }//Copyright (c) 2016 Copyright Holder All Rights Reserved.總結(jié)
以上是生活随笔為你收集整理的进程间通信--无名管道(pipe)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 嵌入式经典面试题
- 下一篇: 进程间通信--命名管道(fifo)