有名管道简单单收单发聊天
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(){
//创建管道A
if(access("pipeA", F_OK) == -1){
printf("creata pipeA \n");
int ret = mkfifo("pipeA", 0664);
if(ret == -1){
perror("pipeA");
return -1;
}
}
//创建管道B
if(access("pipeB", F_OK) == -1){
printf("creata pipeB \n");
int ret = mkfifo("pipeB", 0664);
if(ret == -1){
perror("pipeB");
return -1;
}
}
//A 写 B 读
//A 写
int fdw = open("pipeA", O_WRONLY);
if(fdw == -1){
perror("chatA: write pipeA open");
return -1;
}
printf("chatA: pipeA is opening, waiting write......\n");
//B 读
int fdr = open("pipeB", O_RDONLY);
if(fdr == -1){
perror("chatA: read pipeB open");
return -1;
}
printf("chatA: pipeB is opening, waiting read......\n");
//循环读写
char buf[128];
while(1){
//获取标准输入数据 fgets
memset(buf, 0, 128);
fgets(buf, 128, stdin);
//写数据
int len = write(fdw, buf, sizeof(buf));
if(len == -1){
perror("chatA: write");
return -1;
}
//读数据
char buff[128];
int llen = read(fdr, buff, sizeof(buff));
if(llen <= 0){
perror("chatA: read");
return -1;
}
printf("chatA: %s\n", buff);
}
close(fdw);
close(fdr);
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main(){
//创建管道A
if(access("pipeA", F_OK) == -1){
printf("creata pipeA \n");
int ret = mkfifo("pipeA", 0664);
if(ret == -1){
perror("pipeA");
return -1;
}
}
//创建管道B
if(access("pipeB", F_OK) == -1){
printf("creata pipeB \n");
int ret = mkfifo("pipeB", 0664);
if(ret == -1){
perror("pipeB");
return -1;
}
}
//A 写 B 读
//A 读
int fdr = open("pipeA", O_RDONLY);
if(fdr == -1){
perror("chatB: read pipeA open");
return -1;
}
printf("chatB: pipeA is open, waiting read......\n");
//B 写
int fdw = open("pipeB", O_WRONLY);
if(fdw == -1){
perror("chatB: write pipeB open");
return -1;
}
printf("chatB: pipeB is open, waiting write......\n");
//循环读写
char buf[128];
char buff[128];
while(1){
//读数据
memset(buff, 0, 128);
int llen = read(fdr, buff, sizeof(buff));
if(llen <= 0){
perror("chatB: read");
return -1;
}
printf("chatB: %s\n", buff);
//获取标准输入数据 fgets
memset(buf, 0, 128);
fgets(buf, 128, stdin);
//写数据
int len = write(fdw, buf, sizeof(buf));
if(len == -1){
perror("chatB: write");
return -1;
}
}
close(fdw);
close(fdr);
return 0;
}
只能单收单发
即:
A 发 B收
B发 A收