进程间通信无名pipe和有名fifo(Linux,C)

本文介绍了两种进程间通信方式:无名管道和有名管道(FIFO)。无名管道通过父子进程间的管道进行数据传递,而有名管道允许不相关的进程间通信。详细展示了如何使用C语言实现这两种管道通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 无名管道(PIPE)

#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80

int main(void){
	int n;
	int fd[2]; // 管道两端文件描述符,fd[0]读断,fd[1]写段
	pid_t pid;
	char line[MAXLINE];
	
	if (pipe(fd) < 0) { // 创建管道,成功返回0,失败返回-1
		perror("pipe");
		exit(1);
	}
	
	if ((pid = fork()) < 0) {
		perror("fork");
		exit(1);
	}

	if (pid > 0) { 
		close(fd[0]); // 父进程关闭读端
		write(fd[1], "hello world\n", 12); // 从写端写入
		wait(NULL);
	}
	 else {	 
		close(fd[1]); // 子进程关闭写端
		n = read(fd[0], line, MAXLINE); // 从读端读出
		write(STDOUT_FILENO, line, n); // 打印到屏幕
	}
	return 0;
}

2. 有名管道(FIFO)

发送方:
// sender.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FIFO "./myfifo" 

int main(int argc, char **argv){
	if(access(FIFO, F_OK)){
		mkfifo(FIFO, 0644);
	}
	int fifo = open(FIFO, O_WRONLY); // 以只写方式打开 FIFO
	char msg[20];
	
	while(1){
		bzero(msg, 20);
		fgets(msg, 20, stdin);
		int n = write(fifo, msg, strlen(msg)); // 将数据写入 FIFO
	}
	return 0;
接收方:
// receiver.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FIFO "./myfifo" // 有名管道的名

int main(int argc, char **argv){

	if(access(FIFO, F_OK)){
		mkfifo(FIFO, 0644);
	}
	int fifo = open(FIFO, O_RDONLY); // 以只读方式打开管道
	char msg[20];
	bzero(msg, 20);
	while(1){
		read(fifo, msg, 20); // 将数据从 FIFO 中读出
		printf("from FIFO: %s", msg);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值