Linux 进程通信——fifo

写了两个进程,简述一下fifo原理(我是这么认为的,有什么不对的还请指正)

我觉得他这并不像是管道,而更像对文件的操作。。。

#ifndef _COMMON_H_
#define _COMMON_H_

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

#define MAX_STRING 1024

const char fifo1[] = { "/tmp/fifo1" };
const char fifo2[] = { "/tmp/fifo2" };

#endif

#include "common.h"

void changeLetter(char *string)
{
	int i;
	for ( i = 0; string[i] != '\0'; i++)
	{
		if (string[i] <= 'z'&& string[i] >= 'a')
		{
			string[i] -= 32;
		}
		else if (string[i] <= 'Z'&& string[i] >= 'A')
		{
			string[i] += 32;
		}
	}
}

void main(void)
{
	int fd1, fd2;
	char buf[MAX_STRING];
	//open fifo1 
	fd1 = open(fifo1,O_RDONLY,0777);
	if (fd1<0)
	{
		printf("can`t open fifo:%s\n",fifo1);
		exit(1);
	}
	fd2 = open(fifo2, O_WRONLY, 0777);
	if (fd2<0)
	{
		printf("can`t open fifo:%s\n", fifo2);
		exit(1);
	}
	//main process
	while (1)
	{
		memset(buf,0,MAX_STRING);
		read(fd1,buf,MAX_STRING);
		printf("code process read data:%s\n",buf);
		changeLetter(buf);
		printf("code process change data:%s\n",buf);
		write(fd2,buf,strlen(buf));
		printf("code process send data finished!\n");
	}


}

#include "common.h"

void main()
{
	//fifo id
	int fd1,fd2;
	//file id
	int file1, file2;
	
	char filePath[MAX_STRING];
	int readSize;
	char buf[MAX_STRING];

	//create 1 fifo
	if (-1 == access(fifo1,F_OK))
	{
		if (mkfifo(fifo1,0777)<0)
		{
			printf("can`t create fifo1 %s\n",fifo1);
			exit(1);
		}
	}
	if (-1 == access(fifo2, F_OK))
	{
		if (mkfifo(fifo2, 0777)<0)
		{
			printf("can`t create fifo2 %s\n", fifo2);
			exit(1);
		}
	}
	//open 1 fifo
	fd1 = open(fifo1,O_WRONLY,0777);
	if (fd1<0)
	{
		printf("can`t open fifo1 %s\n",fifo1);
		exit(1);
	}
	fd2 = open(fifo2, O_RDONLY, 0777);
	if (fd2<0)
	{
		printf("can`t open fifo2 %s\n", fifo2);
		exit(1);
	}
	//main process
	while (1)
	{
		//select change code file
		printf("please input your source file path:");
		memset(filePath, 0, sizeof(filePath));
		scanf("%s", filePath);
		file1 = open(filePath, O_RDONLY, 0777);
		if (file1<0)
		{
			printf("file1 can`t open:%s,please input again ",filePath);
			continue;
		}

		//read file1,sand data to fifo1 
		memset(buf, 0, MAX_STRING);
		readSize = read(file1, buf, MAX_STRING);
		write(fd1, buf, readSize+1);
		close(file1);

		//read coed data from fifo2
		memset(buf, 0, MAX_STRING);
		readSize = read(fd2, buf, MAX_STRING);
		printf("received:%s\n",buf);



		//creat and write data to file2
		strcat(filePath, ".changed");
		file2 = open(filePath, O_WRONLY | O_CREAT, 0777);
		if (file2<0)
		{
			printf("can`t create and open %s\n", filePath);
			close(file1);
			continue;
		}
		write(file2, buf, readSize);
		printf("%s the file write done\n ",filePath);
		close(file2);


	}
	close(fd1);
	close(fd2);
}

分析了一下,画了个流程图(     亲民版:D      )



猜你喜欢

转载自blog.csdn.net/zhangzc1026/article/details/80512424