Linuxネーミングパイプ

2006 ワード

//      :
//1.                     ,          ,      
//     open
//      ,        open(DEF_FIFO_PATH,O_RDWR)
//            
//       ,      
//       
//2.     
//3.    ,    
//    

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

#define DEF_FIFO_PATH ("./FIFO")
#define DEF_STD_ERROR (-1)

int main(int argc,char *argv[])
{
        int ret;
        int fd;
        char str[1024];
        //if argv[1] > 0,writer
        if(atoi(argv[1])>0)
		{
			ret = mkfifo(DEF_FIFO_PATH,S_IWUSR | S_IRUSR);
			if(ret == DEF_STD_ERROR)
			{
					if(errno == EEXIST)
					{
							printf("Fifo always exist
"); } else { printf("%d
",strerror(errno)); return -1; } } //open fifo fd = open(DEF_FIFO_PATH,O_WRONLY)//O_WRONLY , if(fd == DEF_STD_ERROR) { printf("%d
",strerror(errno)); //delete pipe ( ) unlink(DEF_FIFO_PATH); return -1; } //write while(1) { printf("Please input string:
"); scanf("%s",str); write(fd,str,strlen(str)+1); if(!strcmp(str,"goodbye")) { break; } } //close fifo close(fd); } else { //if argv[1] <= 0,reader //check fifo ret = access(DEF_FIFO_PATH,W_OK); if(ret == DEF_STD_ERROR) { printf("%d
",strerror(errno)); return -1; } //open fifo fd = open(DEF_FIFO_PATH,O_RDONLY); if(fd == DEF_STD_ERROR) { printf("%d
",strerror(errno)); return -1; } //read fifo while(1) { read(fd,str,sizeof(str)); printf("Receive data:[%s]
",str); if(strcmp("goodbye",str)==0) { break; } } //close fifo close(fd); } return 0; }