[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 @ 2023-02-20 15:57  2235854410  阅读(27)  评论(0编辑  收藏  举报