【申明:本文仅限于自我归纳总结和相互交流,有纰漏还望各位指出。 联系邮箱:Mr_chenping@163.com】
本篇是IPC开篇吧,最近开始研读进程间通信,感知Linux博大精深啊,一步一步来吧。今天先说最原始的通信方式管道,管道分两种,无名管道pipe和有名管道fifo。本篇参考UNIX网络编程之进程间通信相关源码,首先我们来了解无名管道pipe。
无名管道特点:
一、半双工的,数据只能向一个方向流动,需要双方通信时,需要建立起两个管道。
二、只能用于父子进程或者兄弟进程之间(具有亲缘关系的进程)通信。
三、写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。
参考上图代码如下:
/*
** 双向全双工管道。
** 父:父进程把需要读取文件路径写入管道1,然后阻塞读取管道2,收到数据后打印出来
** 子:读取管道1父进程写入管道的路劲,打开后读取文件内容写入管道2
*/
#include "../myipc.h"
#define MAXLINE 512
void client(int readfd, int writefd)
{
size_t len;
ssize_t n;
char buff[MAXLINE];
/* 4read pathname */
fgets(buff, MAXLINE, stdin);
len = strlen(buff); /* fgets() guarantees null byte at end */
if (buff[len-1] == '\n')
len--; /* delete newline from fgets() */
/* 4write pathname to IPC channel */
write(writefd, buff, len);
/* 4read from IPC, write to standard output */
while ( (n = read(readfd, buff, MAXLINE)) > 0)
{
printf("Now read the path file data is :\n");
write(STDOUT_FILENO, buff, n);
}
}
void server(int readfd, int writefd)
{
int fd;
ssize_t n;
char buff[MAXLINE+1];
/* 4read pathname from IPC channel */
if ( (n = read(readfd, buff, MAXLINE)) == 0)
//err_quit("end-of-file while reading pathname");
perror("end-of-file while reading pathname");
buff[n] = '\0'; /* null terminate pathname */
if ( (fd = open(buff, O_RDONLY)) < 0) {
/* 4error: must tell client */
snprintf(buff + n, sizeof(buff) - n, ": can't open, %s\n",
strerror(errno));
n = strlen(buff);
write(writefd, buff, n);
} else {
/* 4open succeeded: copy file to IPC channel */
while ( (n = read(fd, buff, MAXLINE)) > 0)
write(writefd, buff, n);
close(fd);
}
}
int main(int argc, char **argv)
{
int pipe1[2], pipe2[2];
pid_t childpid;
pipe(pipe1); /* create two pipes */
pipe(pipe2);
if ( (childpid = fork()) == 0) { /* child */
close(pipe1[1]);
close(pipe2[0]);
server(pipe1[0], pipe2[1]);
exit(0);
}
/* 4parent */
close(pipe1[0]);
close(pipe2[1]);
client(pipe2[0], pipe1[1]);
waitpid(childpid, NULL, 0); /* wait for child to terminate */
exit(0);
}