|
看了stevens的UNPv2, 上面说mkfifo打开的管道是half-duplex,今天用O_RDWR的方式打开管道,发现可以同时读写。
源代码如下:
/*
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#define MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)
#define FIFO "/tmp/.fifojbug"
int main(void)
{
int fd1, fd2;
ssize_t n;
char buf[10];
pid_t cpid;
if ((mkfifo(FIFO, MODE) < 0) && errno != EEXIST) {
printf("can't make FIFOs %s", FIFO);
perror(NULL);
exit(1);
}
if ( (cpid = fork()) < 0) {
printf("can't fork child\n");
perror(NULL);
exit(1);
}
else if (cpid == 0) { /* child process */
if ( (fd1 = open(FIFO, O_RDWR)) < 0) {
printf("can't open FIFOs %s with O_RDWR mode\n", FIFO);
perror(NULL);
exit(1);
}
if (write(fd1, "client", 6) <= 0) {
printf("child: can't write to fd1\n");
perror("child");
exit(1);
}
printf("child: write: client\n");
sleep(1);
if ( (n = read(fd1, &buf, 10)) != 6) {
printf("child: can't read from fd1\n");
perror("child");
exit(1);
}
buf[n] = 0;
printf("child: read: %s\n", buf);
exit(0);
}
/* parent process */
if ( (fd2 = open(FIFO, O_RDWR)) < 0) {
printf("parent: can't open FIFOs %s with O_RDWR mode\n", FIFO);
perror("parent");
exit(1);
}
if ( (n = read(fd2, buf, 10)) != 6) {
printf("parent: can't read from fd2\n");
perror("parent");
exit(1);
}
buf[n] = 0;
printf("parent: read: %s\n", buf);
if (write(fd2, "parent", 6) != 6) {
printf("can't write to fd2\n");
perror(NULL);
exit(1);
}
printf("parent: write: parent\n");
waitpid(cpid, NULL, 0);
unlink(FIFO);
exit(0);
} |
|