管道
int main()
{
int pipefd[2]; // 0 读端 1 写端
int ret = pipe(pipefd);
if (-1 == ret)
{
perror("创建管道失败\n");
return -1;
}
write(pipefd[1], "hello", 6);
while (1)
{
char buf[10] = {0};
//1、管道中的数据是一次性的,读完就没有了
//2、当管道中没有数据的时候,read 将会阻塞,直到管道中有数据才返回
read(pipefd[0], buf, 10);
printf ("buf = %s\n", buf);
}
close(pipefd[0]);
close(pipefd[1]);
return 0;
}
父子间进程通信
#include <stdio.h>
// 包含pipe、fork
#include <unistd.h>
#include <string.h>
#define SIZE 1024
// 子进程工作: 往管道写数据
// void child_do(int pipefd[2])
void child_do(int *pipefd)
{
// 关闭读端
close(pipefd[0]);
char buf[SIZE] = {0};
while(1)
{
fgets(buf, SIZE, stdin);
write(pipefd[1], buf, strlen(buf));
}
// 关闭写端
close(pipefd[1]);
}
// 父进程工作:从管道读数据
void father_do(int pipefd[2])
{
// 关闭写端
close(pipefd[1]);
char buf[SIZE+1];
while(1)
{
// ssize_t read(int fd, void *buf, size_t count);
ssize_t ret = read(pipefd[0], buf, SIZE);
if (-1 == ret)
{
perror("读文件失败");
}
buf[ret+1] = '\0';
printf ("父进程读到的数据:%s", buf);
}
// 关闭读端
close(pipefd[0]);
}
// 不同进程间的通信本质:进程之间可以看到一份公共资源;
// 而提供这份资源的形式或者提供者不同,造成了通信方式不同,
// 而 pipe就是提供这份公共资源的形式的一种。
// (1)父进程创建管道,得到两个文件描述符指向管道的两端
// (2)父进程fork出子进程,子进程也有两个文件描述符指向同一管道。
// (3)父进程关闭fd[0],子进程关闭fd[1],即父进程关闭管道读端,子进程关闭管道写端(因为管道只支持单向通信)。
// 父进程可以往管道里写,子进程可以从管道里读,管道是用环形队列实现的,
// 数据从写端流入,从读端流出,这样就实现了进程间通信。
int main()
{
// int pipe(int pipefd[2]);
// 0 读端 1 写端
// 1、创建管道
int pipefd[2];
int ret = pipe(pipefd);
// 2、创建子进程
// pid_t fork(void);
pid_t pid = fork();
switch(pid)
{
case -1:
// 创建失败
perror("创建子进程失败");
break;
case 0:
// 子进程
child_do(pipefd);
break;
default:
// 父进程
father_do(pipefd);
break;
}
printf ("\n");
return 0;
}