天天看點

Linux下的有名管道(04)---使用一個管道實作資料的讀寫

環境:Vmware Workstation;CentOS-6.4-x86_64

說明:

實作的程式,類似于shell操作有名管道。

步驟:

1、建立管道fifo1:

[[email protected] mycode]$ mkfifo fifo1
[[email protected] mycode]$ ls
fifo1
           

2、建立并編輯makefile檔案:

.SUFFIXES:.c .o

CC=gcc

SRCS1=readfifo.c
OBJS1=$(SRCS1:.c=.o)
EXEC1=readfifo

SRCS2=writefifo.c
OBJS2=$(SRCS2:.c=.o)
EXEC2=writefifo

start: $(OBJS1) $(OBJS2)
	$(CC) -o $(EXEC1) $(OBJS1)
	$(CC) -o $(EXEC2) $(OBJS2)
	@echo "--------------------------OK------------------------"

.c.o:
	$(CC) -Wall -o [email protected] -c $<

clean:
	rm -rf $(OBJS1) $(EXEC1)
	rm -rf $(OBJS2) $(EXEC2)
           

3、建立讀取管道的源檔案readfifo.c:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *args[])
{
	// 以隻讀方式打開管道
	int fd = open("fifo1", O_RDONLY);
	// 判斷管道是否打開
	if (fd == -1)
	{
		printf("Message : %s\n", strerror(errno));
		return -1;
	}
	
	// 建立緩沖區
	char buf[1024];
	// 清空緩沖區
	memset(buf, 0, sizeof(buf));
	// 拷貝字元串到緩沖區
	strcpy(buf, "hello world");
	// read方法是阻塞的,隻有讀取到内容才會繼續執行
	read(fd, buf, sizeof(buf));
	printf("%s\n", buf);
	// 關閉管道
	close(fd);
	
	return 0;
}
           

4、建立寫入管道的源檔案writefifo.c:

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char *args[])
{
	// 以隻寫的方式打開管道
	int fd = open("fifo1", O_WRONLY);
	// 判斷管道是否打開
	if (fd == -1)
	{
		printf("Message : %s\n", strerror(errno));
		return -1;
	}
	
	// 建立緩沖區
	char buf[1024];
	// 清空緩沖區
	memset(buf, 0, sizeof(buf));
	// 拷貝字元串到緩沖區
	strcpy(buf, "hello world");
	// 将緩沖區的内容寫入到管道中
	write(fd, buf, strlen(buf));
	printf("%s\n", buf);
	// 關閉管道
	close(fd);
	
	return 0;
}
           

5、編譯并執行程式:

[[email protected] mycode]$ make
gcc -Wall -o readfifo.o -c readfifo.c
gcc -Wall -o writefifo.o -c writefifo.c
gcc -o readfifo readfifo.o
gcc -o writefifo writefifo.o
--------------------------OK------------------------
[[email protected] mycode]$ readfifo 
           

6、在另一個終端中執行writefifo:

[[email protected] mycode]$ writefifo
hello world
           

7、檢視第一個終端的執行效果:

[[email protected] mycode]$ readfifo 
hello world
           

PS:根據傳智播客視訊學習整理得出。

繼續閱讀