#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<string.h>
#include<wait.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<fcntl.h>
#define MAX_LINE 80
#define FIFO_SERVER "/tmp/fifoserver"
int main()
{
const char* name ="fifoserver";
unlink(name);
int res=mkfifo(name,0777);
if(res!=0)
{
printf("fail to create pipe\n");
return 0;
}
printf("success to create pipe\n");
int pid=fork();
if(pid==0) //child
{
int pipe_fd=open(name,O_WRONLY); //just write
if(pipe_fd==-1)
{
printf("fail to open\n");
}
char* buf1="Hello world";
printf("child: %d\n",getgid());
int n1=write(pipe_fd,buf1,strlen(buf1));
printf("success to write data: %d bits\n",n1);
close(pipe_fd);
}
else if(pid>0) //parent
{
int data_fd=open(name,O_RDONLY); //just read
char* buf2=(char*)malloc(sizeof(char)*MAX_LINE);
int n2=read(data_fd,buf2,MAX_LINE);
puts(buf2);
printf("parent: %d\n",getppid());
printf("success to read data: %d bits\n",n2);
close(data_fd);
}
else
{
printf("create error\n");
}
return 0;
}