[Linux] 使用管道进行进程间通信

什么是管道

父进程向子进程发送消息

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main()
{
	int fd[2];
	int ret = pipe(fd);
	if (ret == -1) {
		perror("pipe error\n");
		return 1;
	}
	pid_t id = fork();
	if (id == 0) {
		//child
		close(fd[1]); //关闭写端
		char msg[100];
		int j = 0;
		while (j<5) {
			memset(msg,'\0',sizeof(msg));
			ssize_t s = read(fd[0], msg, sizeof(msg));
			if (s>0) {
				msg[s - 1] = '\0';
			}
			printf("%s\n", msg);
			j++;
		}
	}
	else if (id>0) {
		//father
		int i = 0;
		close(fd[0]); // 关闭读端
		char *father = "I am  father!";
		while (i<5) {
			write(fd[1], father, strlen(father) + 1);
			sleep(2);
			i++;
		}
	}
    else {//error
		perror("fork error\n");
		return 2;
	}
	return  0;
}
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# gcc pipe3.c -o pipe3
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# ./pipe3
I am  father!
I am  father!
I am  father!
I am  father!
I am  father!

子进程向父进程发送消息

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main()
{
	int fd[2];
	int ret = pipe(fd);
	if (ret == -1) {
		perror("pipe error\n");
		return 1;
	}
	pid_t id = fork();
	if (id == 0) {
		//child
		int i = 0;
		close(fd[0]); // 关闭读端
		char *father = "I am  child!";
		while (i<5) {
			write(fd[1], father, strlen(father) + 1);
			sleep(2);
			i++;
		}
	}
	else if (id>0) {
		//father
		close(fd[1]); // 关闭写端
		char msg[100];
		int j = 0;
		while (j<5) {
			memset(msg,'\0',sizeof(msg));
			ssize_t s = read(fd[0], msg, sizeof(msg));
			if (s>0) {
				msg[s - 1] = '\0';
			}
			printf("%s\n", msg);
			j++;
		}
	}
    else {//error
		perror("fork error\n");
		return 2;
	}
	return  0;
}
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# gcc pipe2.c -o pipe2
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# ./pipe2
I am  child!
I am  child!
I am  child!
I am  child!
I am  child!
posted @   2235854410  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示