一. 代码段:
① :头文件
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h。
#include <unistd.h>
② 代码段:
#define FIFO_PATH "/tmp/my_fifo"
#define MSG_LENGTH 20
int Fifo_Spreak_Init(); //通信初始化
int Fifo_Spreakint(int fifo_fd); //进行通信
int Fifo_Spreak_Free(); //通信释放
int Fifo_Spreak_Init() // 初始化函数
{
if(access(FIFO_PATH,F_OK))
{
umask(0000);
mkfifo(FIFO_PATH,0777); // 不存在则创建管道
}
int fifo_fd = open(FIFO_PATH,O_RDWR); // 用open打开管道
if(fifo_fd == -1)
{
perror("open");
return -1;
}
return fifo_fd; // 返回fifo_fd
}
int Fifo_Spreakint(int fifo_fd) //进行通信
{
int pid = fork(); // 创建父子进程,分别执行读和写的操作
char msg_data[MSG_LENGTH];
if(pid == -1)
{
perror("fork");
return -1;
}
else if(pid == 0) // 子进程:用来执行读
{
while(1)
{
memset(msg_data,0,MSG_LENGTH);
read(fifo_fd,msg_data,MSG_LENGTH);
printf("小明说:%s\n",msg_data);
}
}
else // 父进程用来执行发送信息
{
while(1)
{
memset(msg_data,0,MSG_LENGTH);
printf("请输入要发送给小明的信息:");
scanf("%s",msg_data);
kill(pid,SIGSTOP);//system("kill -19 ");//用kill,发送给子进程信息,使子进程暂停
sleep(1);
write(fifo_fd,msg_data,strlen(msg_data));
sleep(1);
kill(pid,SIGCONT);
printf("唤醒子进程!\n");
}
}
return 0;
}
int Fifo_Spreak_Free(int fifo_fd) //通信释放
{
close(fifo_fd);
return 0;
}
int main()
{
int fifo_fd = Fifo_Spreak_Init();
if(fifo_fd == -1)
{
printf("管道通初始化失败\n");
return -1;
}
Fifo_Spreakint(fifo_fd); //进行通信
Fifo_Spreak_Free(fifo_fd);
return 0;
}
③ :另外创建一个文件和此文件代码相同,然后gcc编译,运行
二、具体实现效果