为实现两个独立进程之间的通信,我们需要给两个独立的进程创建子进程和父进程。
利用fork()函数创建进程的子进程和父进程。
进程1中子进程用来发送数据给进程2中的子进程,进程2中的父进程发送数据给进程1中的父进程。
发送和接收过程中运用到文件的读写函数 write()和read()。
两个进程的创建与通信如图:
进程1中的创建父子进程以及接收发送:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#define FIFO1 "myfifo1"
#define FIFO2 "myfifo2"
int main(int argc, const char *argv[])
{
pid_t pid;
pid = fork();
if(pid < 0)
{
perror("fork error!");
return -1;
}
//子进程发送
if(pid == 0)
{
if(mkfifo(FIFO