#include<stdio.h>#include<unistd.h>#include<string.h>#include<errno.h>intmain()
{
int fd[2];
int ret = pipe(fd);
if (ret == -1) {
perror("pipe error\n");
return1;
}
pid_t id = fork();
if (id == 0) {
//child
close(fd[1]); //关闭写端char msg[100];
int j = 0;
while (j<5) {
memset(msg,'\0',sizeof(msg));
ssize_t s = read(fd[0], msg, sizeof(msg));
if (s>0) {
msg[s - 1] = '\0';
}
printf("%s\n", msg);
j++;
}
}
elseif (id>0) {
//fatherint i = 0;
close(fd[0]); // 关闭读端char *father = "I am father!";
while (i<5) {
write(fd[1], father, strlen(father) + 1);
sleep(2);
i++;
}
}
else {//error
perror("fork error\n");
return2;
}
return0;
}
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# gcc pipe3.c -o pipe3
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# ./pipe3
I am father!
I am father!
I am father!
I am father!
I am father!
子进程向父进程发送消息
#include<stdio.h>#include<unistd.h>#include<string.h>#include<errno.h>intmain()
{
int fd[2];
int ret = pipe(fd);
if (ret == -1) {
perror("pipe error\n");
return1;
}
pid_t id = fork();
if (id == 0) {
//childint i = 0;
close(fd[0]); // 关闭读端char *father = "I am child!";
while (i<5) {
write(fd[1], father, strlen(father) + 1);
sleep(2);
i++;
}
}
elseif (id>0) {
//father
close(fd[1]); // 关闭写端char msg[100];
int j = 0;
while (j<5) {
memset(msg,'\0',sizeof(msg));
ssize_t s = read(fd[0], msg, sizeof(msg));
if (s>0) {
msg[s - 1] = '\0';
}
printf("%s\n", msg);
j++;
}
}
else {//error
perror("fork error\n");
return2;
}
return0;
}
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# gcc pipe2.c -o pipe2
(base) root@iZuf65cax8rsfekcyp3ytyZ:~/testfork# ./pipe2
I am child!
I am child!
I am child!
I am child!
I am child!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现