有关函数:
fork();
NAME
fork - create a child process
SYNOPSIS
#include <unistd.h>
pid_t fork(void);
mkfifo();
NAME
mkfifo, mkfifoat - make a FIFO special file (a named pipe)
SYNOPSIS
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
kill();
NAME
kill - send signal to a process
SYNOPSIS
#include <sys/types.h>
#include <signal.h>
int kill(pid_t pid, int sig);
strcmp();
NAME
strcmp, strncmp - compare two strings
SYNOPSIS
#include <string.h>
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);
编程思路:
实现双方互相通信,实现如图所下的功能。
完成一部分父进程1(写)——>子进程2(读)的功能,另外一部分同理。
先通过fork函数创建父进程与子进程:
先判断是否在指定路径下创建成功fifo1、fifo2后通过open同时打开函数打开所创建的管道fifo1,fifo2,
父进程1发送,利用循环while(1),先对其定义的数组空间进行清零bezro,从键盘获取输入的字符,再用write函数写入,循环对指定路径写入,当从键盘中获取到‘end’字符中使用kill函数。
子进程2接收,同理运用while(1),先对其定义的数组空间进行清零bezro,用read函数循环读取数据,当键盘中获取到'end字符'使用kill函数。
最后使用close函数关闭。
编程代码1:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#define FIFO_FILE_1 "/home/gec/fifo1"
#define FIFO_FILE_2 "/home/gec/fifo2"
int main(int argc, char const *argv[])
{
if (access(FIFO_FILE_1, F_OK) == -1)//判断是否存在fifo1文件
{
if (mkfifo(FIFO_FILE_1, 0777) == -1)
{
perror("mkfifo failed!");
return -1;
}
}
if (access(FIFO_FILE_2, F_OK) == -1)//判断是否存在fifo2文件
{
if (mkfifo(FIFO_FILE_2, 0777) == -1)
{
perror("mkfifo failed!");
return -1;
}
}
int fd_1 = open(FIFO_FILE_1, O_RDWR);
int fd_2 = open(FIFO_FILE_2, O_RDWR);
if (fd_2 < 0 || fd_1 < 0)
{
perror("open fail!");
return -1;
}
pid_t id = fork();
if (id == -1)
{
perror("fork id failed!");
return -1;
}
else if (id > 0) // 父进程1发送
{
char buf_1[1024] = {0};
int ret_1 = 0;
char strcmp_function[4] = {"end"};
while (1)
{
bzero(buf_1, sizeof(buf_1));
printf("please input string:\n");
scanf("%s", buf_1);
ret_1 = write(fd_1, buf_1, strlen(buf_1));
if (strcmp(buf_1, strcmp_function) == 0)
{
kill(0,SIGKILL);
break;
}
}
}
else if (id == 0) // 子进程2收
{
char buf_2[1024];
char strcmp_function[4] = {"end"};
while (1)
{
bzero(buf_2, sizeof(buf_2));
read(fd_2, buf_2, sizeof(buf_2));
printf("Child process 2 reserve:%s\n",buf_2);
if (strcmp(buf_2, strcmp_function) == 0)
{
kill(getppid(),SIGKILL);
break;
}
}
}
close(fd_1);
close(fd_2);
return 0;
}
编程代码2(同理)
运行结果: