先启动服务端,./server &,然后启动客户端,输入一个文件名 服务端:server.c
#include
#include
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include /* Obtain O_* constant definitions */
#include
#include
#include
#include
#include
#include
#include
#include
#include
void server(int, int);
#define FIFO1 "/tmp/fifo.1"
#define FIFO2 "/tmp/fifo.2"
#define MAXLINE 4096 /* max text line length */
#define FILE_MODE(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
/* 1.mkfifo已经隐含指定了O_CREAT|O_EXCL */
/* 2.没有写fifo就打开读会阻塞,反过来也是一样 */
/* 3.可以指定O_NONBLOCK设置非阻塞,但是pipe不行
注意:在这种情况下,已经open FIFO写的时候再打开会返回ENXIO错误 */
/* 4.也可以用fcntl设置非阻塞 */
/* 5.请求写入字节 0)
write(writefd, buff, n);
close(fd);
}
}
客户端:client.c
#include
#include
#define _GNU_SOURCE /* See feature_test_macros(7) */
#include /* Obtain O_* constant definitions */
#include
#include
#include
#include
#include
#include
#include
#include
#include
void client(int, int);
#define FIFO1 "/tmp/fifo.1"
#define FIFO2 "/tmp/fifo.2"
#define MAXLINE 4096 /* max text line length */
#define FILE_MODE(S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
int main(int argc, char **argv)
{
int readfd, writefd;
writefd = open(FIFO1, O_WRONLY, 0);
assert(writefd!=-1);
readfd = open(FIFO2, O_RDONLY, 0);
assert(readfd!=-1);
client(readfd, writefd);
close(readfd);
close(writefd);
unlink(FIFO1);
unlink(FIFO2);
exit(0);
}
void client(int readfd, int writefd)
{
size_t len;
ssize_t n;
char buff[MAXLINE];
/* 4read pathname */
fgets(buff, MAXLINE, stdin);
len = strlen(buff); /* fgets() guarantees null byte at end */
if (buff[len-1] == '\n')
len--; /* delete newline from fgets() */
/* 4write pathname to IPC channel */
write(writefd, buff, len);
/* 4read from IPC, write to standard output */
while ( (n = read(readfd, buff, MAXLINE)) > 0)
write(STDOUT_FILENO, buff, n);
}