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

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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章