一.思维导图
二.练习
1) 模拟聊天界面
1.create.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
int main(int argc, const char *argv[]) {
//创建管道文件
if (mkfifo("./pipe1", 0664)) {
perror("create error");
return -1;
}
if (mkfifo("./pipe2", 0664)) {
perror("create error");
return -1;
}
//阻塞等待其他进程使用管道
getchar();
//用代码执行终端指令,结束时,删除myfifo
system("rm pipe1");
system("rm pipe2");
return 0;
}
- write.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
int main(int argc, const char *argv[]) {
char buf[128] = "";
pid_t pid = fork();
if (pid < 0) {
perror("fork error");
return -1;
} else if (pid == 0) {
//子进程,负责读
int rfd; //文件描述符
if ((rfd = open("./pipe2", O_RDONLY)) == -1) {
perror("open wfd error");
return -1;
}
while(1) {
memset(buf, 0, sizeof(buf));
read(rfd, buf, sizeof(buf));
if (strcmp(buf, "quit") == 0) {
break;
}
printf("%s\n", buf);
}
} else {
//父进程,负责写
int wfd;
if ((wfd = open("./pipe1", O_WRONLY)) == -1) {
perror("open error");
return -1;
} //循环往管道中写数据
while(1) {
fgets(buf, sizeof(buf), stdin);
//清掉'\n'
buf[strlen(buf)-1] = '\0';
//将数据写入管道中
write(wfd, buf, strlen(buf));
//如果输入的是quit
if (strcmp(buf, "quit") == 0) {
break;
}
}
//关闭文件
close(wfd);
wait(NULL);
}
return 0;
}
- read.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
#include <pthread.h>
int main(int argc, const char *argv[]) {
char buf[128] = "";
pid_t pid = fork();
if (pid < 0) {
perror("fork error");
return -1;
} else if (pid == 0) {
//子进程,负责读
int rfd; //文件描述符
if ((rfd = open("./pipe1", O_RDONLY)) == -1) {
perror("open wfd error");
return -1;
}
while(1) {
memset(buf, 0, sizeof(buf));
read(rfd, buf, sizeof(buf));
if (strcmp(buf, "quit") == 0) {
break;
}
printf("%s\n", buf);
}
} else {
//父进程,负责写
int wfd;
if ((wfd = open("./pipe2", O_WRONLY)) == -1) {
perror("open error");
return -1;
} //循环往管道中写数据
while(1) {
fgets(buf, sizeof(buf), stdin);
//清掉'\n'
buf[strlen(buf)-1] = '\0';
//将数据写入管道中
write(wfd, buf, strlen(buf));
//如果输入的是quit
if (strcmp(buf, "quit") == 0) {
break;
}
}
//关闭文件
close(wfd);
wait(NULL);
}
return 0;
}
结果展示: