1. 程式人生 > >Linux 程序通訊之 命名管道

Linux 程序通訊之 命名管道

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
	int fb = open("./log", O_WRONLY); 
	if(fb < 0){
		perror("open");
		return 2;
	}
	
	char buf[128];
	while(1){
		printf("please enter:");
		fflush(stdout);
		ssize_t _a = read(0, buf, sizeof(buf)-1);
		if(_a > 0 ){
			buf[_a-1] = '\0';
			ssize_t _s = write(fb, buf, strlen(buf));
		}else{
			perror("write");
			return 3;
		}

	}
	close(fb);
	return 0;
}
server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
	if(mkfifo("./log", 0666|S_IFIFO) < 0){
		perror("mkfifo");
		return 1;
	}

	int fb = open("./log", O_RDONLY); 
	if(fb < 0){
		perror("open");
		return 2;
	}
	
	char buf[128];
	while(1){
		ssize_t _s = read(fb, buf, sizeof(buf)-1);
		if(_s > 0 ){
			buf[_s] = '\0';
			printf("%s\n",buf);
		}else if(_s == 0){
			printf("client is qute, i am quiting\n");
			break;
		}else{
			perror("read");
			return 3;
		}

	}
	close(fb);
	return 0;
}
結果演示: