管道
#include <stdio.h>
#include <unistd.h>
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>
#include <unistd.h>
#include <string.h>
#define SIZE 1024
// 子进程工作: 往管道写数据
void child_do(int pipefd[2])
{
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] = {0};
while (1)
{
ssize_t ret = read(pipefd[0], buf, SIZE);
if (-1 == ret)
{
perror("父进程读数据失败");
break;
}
buf[ret] = '\0';
printf ("父进程读到数据:%s\n", buf);
}
close (pipefd[0]); // 关闭读端
}
int main()
{
// 1、创建管道
int pipefd[2]; // 0 读端 1 写端
int ret = pipe(pipefd);
if (-1 == ret)
{
perror("创建管道失败");
return -1;
}
// 2、创建子进程
pid_t pid = fork();
switch(pid)
{
case 0: // 子进程
child_do(pipefd);
break;
case -1: // 创建失败
perror("子进程创建失败");
break;
default: // 父进程
father_do(pipefd);
break;
}
return 0;
}
命名管道
1、创建
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
int main()
{
int ret = mkfifo("/home/myfifo", 0766);
if (-1 == ret)
{
perror("管道文件创建失败");
return -1;
}
return 0;
}
2、写管道文件
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 1024
int main()
{
int fd = open("/home/myfifo", O_WRONLY);
if (-1 == fd)
{
perror ("打开文件失败");
return -1;
}
char buf[SIZE] = {0};
while (1)
{
fgets(buf, SIZE, stdin);
write(fd, buf, strlen(buf));
}
close (fd);
return 0;
}
3、读管道文件
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define SIZE 1024
int main()
{
int fd = open("/home/myfifo", O_RDONLY);
if (-1 == fd)
{
perror ("打开文件失败");
return -1;
}
char buf[SIZE+1] = {0};
while (1)
{
ssize_t ret = read(fd, buf, SIZE);
if (-1 == ret)
{
perror("父进程读数据失败");
break;
}
buf[ret] = '\0';
printf ("读到数据:%s\n", buf);
}
close (fd);
return 0;
}
4、非阻塞读管道文件
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define SIZE 1024
int main()
{
int fd = open("/home/myfifo", O_RDONLY | O_NONBLOCK);
if (-1 == fd)
{
perror ("打开文件失败");
return -1;
}
char buf[SIZE+1] = {0};
while (1)
{
ssize_t ret = read(fd, buf, SIZE);
if (-1 == ret)
{
if (errno == EAGAIN)
{
printf("无数据可读\n");
sleep(2);
continue;
}
perror("父进程读数据失败");
break;
}
buf[ret] = '\0';
printf ("读到数据:%s\n", buf);
}
close (fd);
return 0;
}