- 匿名管道
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<errno.h>
#include<sys/mman.h>
#include<pthread.h>
void writer(const char *message,int count,FILE *stream)
{
for(;count>0;--count)
{
fprintf(stream,"%s\n",message);
fflush(stream);
sleep(1);
}
}
void reader(FILE *stream)
{
char buffer[1024];
while(!feof(stream)&&!ferror(stream)&&fgets(buffer,sizeof(buffer),stream)!=NULL)
fputs(buffer,stdout);
}
int main()
{
int fds[2];
pid_t pid;
pipe (fds);
pid=fork();
if(pid==0)
{
FILE *stream;
close(fds[1]);
stream=fdopen(fds[0],"r");
reader(stream);
close(fds[0]);
}
else
{
FILE *stream;
close(fds[0]);
stream=fdopen(fds[1],"w");
writer("Hello,world!",5,stream);
close(fds[1]);
}
return 0;
}
- 有名管道
写程序:
#include<stdio.h>
#include<stdlib.h>
#include<semaphore.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<errno.h>
#include<sys/mman.h>
#include<pthread.h>
#include<sys/stat.h>
#include<fcntl.h>
#define FIFO "myfifo"
#define BUFF_SIZE 1024
int main(int argc,char* argv[])
{
char buff[BUFF_SIZE];
int real_write;
int fd;
if(argc<=1)
{
printf("Usage:./fifo_write filename\n");
exit(1);
}
sscanf(argv[1],"%s",buff);
//测试FIFO是否存在,若不存在,则创建一个FIFO
if(access(FIFO,F_OK)==-1)
{
if((mkfifo(FIFO,0666)<0)&&(errno!=EEXIST))
{
printf("Can not create fifo file\n");
exit(1);
}
}
//调用open以只写方式打开FIFO,返回文件描述符fd
if((fd=open(FIFO,O_WRONLY))==-1)
{
printf("open fifo error\n");
exit(1);
}
//调用write将buff写到文件描述符fd指向的FIFO中
if((real_write=write(fd,buff,BUFF_SIZE))>0)
{
printf("Write into pipe:'%s'.\n",buff);
exit(1);
}
close(fd);
return 0;
}
读程序:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<errno.h>
#include<unistd.h>
#include<fcntl.h>
#define FIFO "myfifo"
#define BUFF_SIZE 1024
int main()
{
char buff[BUFF_SIZE];
int real_read;
int fd;
if((access(FIFO,F_OK)==1))
{
if((mkfifo(FIFO,0666)<0)&&(errno!=EEXIST))
{
printf("Can not create fifo file\n");
exit(1);
}
}
if((fd=open(FIFO,O_RDONLY))==-1)
{
printf("Open fifo error\n");
exit(1);
}
while(1)
{
memset(buff,0,BUFF_SIZE);
if((real_read=read(fd,buff,BUFF_SIZE))>0)
{
printf("Read from pipe:'%s'.\n",buff);
}
}
close(fd);
exit(0);
}