#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#define MAX 1024
#define FIFO_SERV "/home/ipc/fifo_serv"
int main(int argc, char* argv[])
{
pid_t pid;
int prfd, pwfd;
int recvBytes, sendBytes;
char recvBuf[MAX], sendBuf[MAX];
memset(recvBuf, 0, MAX);
memset(sendBuf, 0, MAX);
if ((pid = fork()) == 0) {
printf("child begin.\n");
if ((prfd = open(FIFO_SERV, O_RDONLY, 0)) == -1) {
perror("child open FIFO_SERV:");
exit(1);
}
recvBytes = read(prfd, recvBuf, MAX);
if (recvBytes == -1 && errno == EAGAIN) {
printf("no data available; try later\n");
}
printf("recv %d Bytes data:%s\n", recvBytes, recvBuf);
unlink(FIFO_SERV);
printf("child end.\n");
} else if (pid > 0) {
printf("parent begin.\n");
if ((mkfifo(FIFO_SERV, O_CREAT|O_EXCL|0777) < 0) && (errno != EEXIST)) {
printf("cannot create fifoserver\n");
}
if ((pwfd = open(FIFO_SERV, O_WRONLY, 0)) == -1) {
perror("father open FIFO_SERV");
exit(1);
}
strcpy(sendBuf, "Name pipe test!");
sendBytes = write(pwfd, sendBuf, MAX);
if (sendBytes == -1 && errno == EAGAIN) {
printf("write to fifo error; try later\n");
}
printf("send %d Bytes data:%s\n", sendBytes, sendBuf);
unlink(FIFO_SERV);
sleep(2);
printf("parent end.\n");
} else {
perror("fork:");
exit(1);
}
exit(0);
}
下面几点需要特别注意:
1)管道名错误,无法创建有名管道
2)注释掉子进程中的接收部分,测试结果为父进程依然能向管道发送数据。
3)注释掉父进程中的发送部分,测试结果为子进程依然能从管道接收数据,recvBytes = 0。
4)有名管道可以看作无名管道的升级版,克服了只能在亲缘关系进程间使用的门槛。
5)由于需要通过文件操作,在通信速度上不具有优势
6)有名管道设置为非阻塞模式时,可以通过select监听管道的读写
参考:http://hi.baidu.com/erics_lele/item/1c5a06732b168f5f0c0a0722