方法一:使用两个管道实现两个.c文件,本文只提供了一个.c另一个.c文件copy过去父子进程的收发交换一下即可。
代码:
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#define PATH1 "/tmp/fifo"
#define PATH2 "/tmp/fifo1"
int main()
{
if (access(PATH1, F_OK))
{
umask(0000);
//创建管道文件
mkfifo(PATH1, 0777);
}
if (access(PATH2, F_OK))
{
umask(0000);
//创建管道文件
mkfifo(PATH2, 0777);
}
//打开管道文件
int fd1 = open(PATH1, O_RDWR);
if (fd1 == -1)
{
perror("open failed");
exit(-1);
}
int fd2 = open(PATH2, O_RDWR);
if (fd2 == -1)
{
perror("open failed");
exit(-1);
}
pid_t ret = fork(); //创建进程
if (ret == -1)
{
perror("fork");
exit(-1);
}
else if (ret == 0) //子进程
{
char msg_Tom[32] = {0};
while (1)
{
memset(msg_Tom, 0, 32);
scanf("%s", msg_Tom);
write(fd1, msg_Tom, strlen(msg_Tom));
}
}
else //父进程
{
char msg_Tom[32] = {0};
while (1)
{
memset(msg_Tom, 0, 32);
printf("Jack:");
read(fd2, msg_Tom, 32);
printf("%s\n", msg_Tom);
}
}
close(fd1);
close(fd2);
return 0;
}
方法二:使用一个管道实现:
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>//exit
#include <string.h>//memset
#include <errno.h>
#include <sys/types.h>//fork
#include <sys/wait.h>//wait
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>//fork pipe
#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);
if(fifo_fd == -1)
{
perror("open");
return -1;
}
return fifo_fd;
}
int Fifo_Spreakint(int fifo_fd)//进行通信
{
int pid = fork();
if(pid == -1)
{
perror("fork");
return -1;
}
else if(pid == 0)
{
char msg_data[MSG_LENGTH];
while(1)
{
memset(msg_data,0,MSG_LENGTH);
read(fifo_fd,msg_data,MSG_LENGTH);
printf("小红说:%s\n",msg_data);
}
}
else
{
char msg_data[MSG_LENGTH];
while(1)
{
memset(msg_data,0,MSG_LENGTH);
printf("请输入要发送给小红的信息:");
scanf("%s",msg_data);
kill(pid,SIGSTOP);//system("kill -19 ");
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;
}