完成父子进程的通信,
父进程发送一句话后,子进程接收打印
然后子进程发送一句话,父进程接收后打印
#include "head.h"
#define buf_size 256
int main(int argc, const char *argv[])
{
int fd[2];
pid_t pid;
char buf[buf_size];
char msg1[] = "Hello child";
char msg2[] = "Hello Parent!";
// 创建管道
if (pipe(fd) == -1)
{
perror("pipe");
exit(EXIT_FAILURE);
}
while(1)
{
// 创建子进程
pid = fork();
if (-1 == pid)
{
perror("fork");
exit(EXIT_FAILURE);
}
if (0 == pid)
{
// 子进程
close(fd[1]); // 关闭写端
// 接收父进程发送的消息
read(fd[0], buf, buf_size);
printf("Child recv: %s\n", buf);
// 发送消息给父进程
write(fd[1], msg2, strlen(msg2) + 1);
printf("Child send: %s\n", msg2);
close(fd[0]); // 关闭读端
}
else if(0 < pid)
{
// 父进程
close(fd[0]); // 关闭读端
// 发送消息给子进程
write(fd[1], msg1, strlen(msg1) + 1);
printf("Parent send: %s\n", msg1);
// 等待子进程结束
wait(NULL);
// 接收子进程发送的消息
read(fd[0], buf, buf_size);
printf("Parent recv: %s\n", buf);
close(fd[1]); // 关闭写端
}
}
return 0;
}