创建两个有名管道来实现不同进程间的全双工通信。
两个进程聊天程序:一个server端,一个client端。
例子用到了read函数:
read函数只是一个通用的读文件设备的接口。是否阻塞需要由设备的属性和设定所决定。一般来说,读字符终端、网络的socket描述字,管道文件等,这些文件的缺省read都是阻塞的方式。
如果是读磁盘上的文件,一般不会是阻塞方式的。但使用锁和fcntl设置取消文件O_NOBLOCK状态,也会产生阻塞的read效果。
server端:
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FIFO_WRITE "readfifo"
#define FIFO_READ "writefifo"
#define LEN 300
int main(int argc, char* argv[])
{
char buf[LEN];
char readbuf[LEN];
int wfd;
int rfd;
int len;
mkfifo(FIFO_WRITE, S_IFIFO|0666);
rfd = open(FIFO_READ, O_RDONLY);
wfd = open(FIFO_WRITE, O_WRONLY);
while(1)
{
bzero(readbuf, LEN);
len = read(rfd, readbuf, LEN);
printf("len=%d\n", len);
if (len > 0)
{
readbuf[len] = '\0';
printf("client: %s\n", readbuf);
if (strncmp("quit", readbuf, strlen(readbuf)) == 0)
{
break;
}
}
bzero(buf, LEN);
printf("server: ");
fgets(buf, LEN, stdin);
buf[strlen(buf)-1] = '\0';
write(wfd, buf, strlen(buf));
}
close(wfd);
unlink(FIFO_WRITE);
close(rfd);
return 0;
}
client端:
#include <stdio.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FIFO_READ "readfifo"
#define FIFO_WRITE "writefifo"
#define LEN 300
int main(int argc, char* argv[])
{
char buf[LEN];
char readbuf[LEN];
int wfd;
int rfd;
int len;
mkfifo(FIFO_WRITE, S_IFIFO|0666);
wfd = open(FIFO_WRITE, O_WRONLY);
rfd = open(FIFO_READ, O_RDONLY);
while(1)
{
bzero(buf, LEN);
printf("client: ");
fgets(buf, LEN, stdin);
buf[strlen(buf)-1] = '\0';
write(wfd, buf, strlen(buf));
printf("buf:%s\n", buf);
if (strncmp("quit", buf, strlen(buf)) == 0)
{
break;
}
bzero(readbuf, LEN);
len = read(rfd, readbuf, LEN);
if (len > 0)
{
readbuf[len] = '\0';
printf("server: %s\n", readbuf);
}
}
close(wfd);
unlink(FIFO_WRITE);
close(rfd);
return 0;
}