一、实验目的
1、了解有名管道通信的原理;
2、掌握有名管道的创建及使用方法。
二、实验内容
1、编写以非阻塞方式打开的写进程,其功能为接收用户从键盘输入的字符串,写入FIFO;
2、编写以非阻塞方式打开的读进程,功能为从FIFO中读取数据并打印到终端,遇到字符’p’时暂停读取数据;
3、编译并执行读进程、写进程。
三、源程序
fiforead.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
const char *fifo_name = "/tmp/my_fifo";
const int open_mode = O_RDONLY;
const char *open_mode_name = "O_RDONLY";
int pipe_fd = -1;
printf("进程%d以%s打开有名管道%s\n", getpid(), open_mode_name, fifo_name);
pipe_fd = open(fifo_name, open_mode);
printf("Process %d result %d\n",getpid(), pipe_fd);
if(pipe_fd != -1)
{
char buffer[PIPE_BUF + 1];
memset(buffer, '\0', sizeof(buffer));
int bytes_read = read(pipe_fd, buffer, PIPE_BUF);
buffer[bytes_read] = '\0';
printf("接收到数据为:\n");
while(bytes_read > 0)
{
bool isBreak = false;
for(int i=0; i
fifowrite.c:
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
const char *fifo_name = "/tmp/my_fifo";
const int open_mode = O_WRONLY;
const char *open_mode_name = "O_WRONLY";
if(access(fifo_name, F_OK) == -1)
{
printf ("正在创建有名管道\n");
int res = mkfifo(fifo_name, 0777);
if(res != 0)
{
printf("创建有名管道%s失败%d\n", fifo_name, res);
exit(EXIT_FAILURE);
}
printf("创建有名管道%s成功\n", fifo_name);
}
printf("进程%d以%s打开有名管道%s\n", getpid(), open_mode_name, fifo_name);
int pipe_fd = open(fifo_name, open_mode);
printf("进程%d,结果:%d\n", getpid(), pipe_fd);
if(pipe_fd != -1)
{
char input[256];
memset(input, '\0', sizeof(input));
printf("请输入字符串:\n");
int res = scanf("%[^\n]", input);
if(res!=1)
{
close(pipe_fd);
printf ("输入数据失败\n");
return -1;
}
int len = strlen(input);
int res1 = write(pipe_fd, input, len);
if(res1 == -1)
{
printf("写入管道失败\n");
exit(EXIT_FAILURE);
}
close(pipe_fd);
}
else
{
printf("管道读写失败");
exit(EXIT_FAILURE);
}
printf("进程%d结束\n", getpid());
exit(EXIT_SUCCESS);
}
四、实验步骤、结果截图
(1)编译fiforead.c和fifowrite.c:
(2)运行程序
1. 运行fifowrite.c.o:
2. 运行fiforead.c.o:
fifowrite.c.o窗口运行结果变为:
3. 输入字符串“Thinking in PHP!”,结果如下:
fifowrite.c.o窗口运行结果:
fiforead.c.o窗口运行结果: