写端
#include "stdio.h"
#include "fcntl.h"
#include "sys/stat.h"
#include "string.h"
#include "unistd.h"
int main(void) {
// 创建有名管道
if (mkfifo("./p", 0666) == -1) {
perror("makefifo");
return -1;
}
// 打开管道
int f = open("p", O_WRONLY);
for (;;) {
// 循环往管道里写数据
char buf[128];
// 从键盘输入中读取字符
fgets(buf, sizeof(buf), stdin);
if (strcmp(buf, "!\n")==0) {
// 如果读如!退出程序
break;
}
if (write(f, buf, strlen(buf)) == -1) {
perror("write");
return -1;
}
}
if (close(f) == -1) {
perror("close");
return -1;
}
if (unlink("./p") == -1) {
perror("unlink");
return -1;
}
return 0;
}
读端
#include "stdio.h"
#include "unistd.h"
#include "fcntl.h"
#include "string.h"
int main(void) {
printf("PID:%d\n", getpid());
int f = open("./p", O_RDONLY);
for (;;) {
char buf[128];
int flag = read(f, buf, sizeof(buf));
if ( flag == -1) {
perror("read");
return -1;
}
if (flag == 0) {
break;
}
printf("%s", buf);
}
if (close(f) == -1) {
perror("close");
return -1;
}
return -1;
}