Linux进程间通信(1):管道

接上一篇的内容——Linux任务、进程和线程

参考书籍:《从实践中学嵌入式linux应用程序开发》(华清远见嵌入式学院)

资料下载:

参考链接:

 

Linux进程间通信:

1、同主机进程间数据交互机制:无名管道(PIPE)、有名管道(FIFO)、消息队列(Message Queue)和共享内存(Share Memory)。 2、同主机进程间同步机制:信号量(semaphore)。3、同主机进程间异步机制:信号(Signal)。4、网络主机间数据交互机制:套接字(Socket)

 

无名管道(pipe):

首先是 int pipe(int f[2]) 这个函数,其需要头文件<unistd.h>,这个函数将创建一个未命名管道,香港服务器,并将管道的读端描述字包含在f[0]中,将写端描述字放在f[1]中,然后你就可以像利用普通文件描述字一样来读写数据了。 再次是int close(int fd) 函数, 其需要头文件<unistd.h>,其用于关闭指定的文件描述字。最后是write和read函数, 其需要头文件<unistd.h>,用于读写数据。

无名管道的特点:     1、管道是半双工的,数据只能向一个方向流动,具有固定的读端和写端;需要双方通信时,需要建立起两个管道;    2、只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程);    3、单独构成一种独立的文件系统:管道对于管道两端的进程而言,就是一个文件,但它不是普通的文件,它不属于某种文件系统,而是单独构成一种文件系统,并且只存在与内存中。    4、数据的读出和写入:一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。

管道读写注意点:

/*pipe.c*/

#include <stdio.h>#include <unistd.h>#include <string.h>#include <stdlib.h>#define BUFF_SZ 256int main(){printf();pid_tpid;intpipe_fd[2];charbuf[BUFF_SZ];;intbytes_read;intbytes_write;//clear buffer, all bytes as 0memset(buf, 0, sizeof(buf));(pipe(pipe_fd) < 0)//创建管道{printf();exit(1);}(0 == (pid=fork()))//创建一个子进程{//close the write-point of pipe in child processclose(pipe_fd[1]);((bytes_read = read(pipe_fd[0], buf, BUFF_SZ)) > 0)//子进程读取管道内容{printf(, bytes_read, buf);}//close read-point of pipe in child processclose(pipe_fd[0]);//关闭子进程读描述符exit(0);}//close read-point of pipe in parent processclose(pipe_fd[0]);((bytes_write = write(pipe_fd[1], data, strlen(data)))){printf(, bytes_write, data);}//close write-point of pipe in parent processclose(pipe_fd[1]);//wait child process exitwaitpid(pid, NULL, 0);//收集子进程退出信息printf();return 0;}

标准流管道:

标准流管道完成的工作:

使用实例:

#include<stdio.h>#include<stdlib.h>#include<unistd.h>#include<fcntl.h>#define BUFSIZE 1024int main(){FILE *fd;;char buf[BUFSIZE];))==NULL)//调用popen函数执行相应的命令 {printf();exit(1);}while((fgets(buf,BUFSIZE,fd)) != NULL){printf(,buf);}pclose(fd);//关闭流管道 exit(0);}

有名管道(FIFO):

函数 int mkfifo (char* path, mode_t mode) 负责创建FIFO管道,其需要头文件<sys/stat.h>,参数path即要创建的管道文件存放位置,服务器空间,mode参数即文件权限。更多的参考:。     FIFO管道创建完成以后,虚拟主机,便可以使用open函数来打开它,然后进行读写操作了。

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <limits.h>#include <sys/types.h>#include <sys/stat.h>#include <unistd.h>

#define BUFFER_SIZE PIPE_BUF#define FIFO_NAME "/tmp/my_fifo"

int main(){int pipe_fd;(access(FIFO_NAME, F_OK) == -1){//creat FIFO pipe filemkfifo(FIFO_NAME, 0777);}//open FIFO pipe file.pipe_fd = open(FIFO_NAME, O_WRONLY);//write data into pipe write(pipe_fd, , PIPE_BUF);//close FIFO pipe file descriptor close(pipe_fd);return 0;}

一个人去旅行,而且是去故乡的山水间徜徉。

Linux进程间通信(1):管道

相关文章:

你感兴趣的文章:

标签云: