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