#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<sys/wait.h>
void sys_err(const char *str)
{ perror(str); exit(1); }
int main(void)
{
pid_t pid; char buf[1024];
int fd[2]; //定义文件描述符数组
char *p = “test for pipe\n”;
if (pipe(fd) == -1) sys_err(“pipe”);
pid = fork();
if (pid < 0) { sys_err(“fork err”); }
else if (pid == 0) { //子进程-读
close(fd[1]); //关闭写端
int len = read(fd[0], buf, sizeof(buf)); //读数据
write(STDOUT_FILENO, buf, len);
close(fd[0]);
} else { //父进程-写
close(fd[0]); //关闭读端
write(fd[1], p, strlen§); //写数据
wait(NULL);
close(fd[1]);
}
return 0;
}
linux 父子进程 源码
最新推荐文章于 2025-08-27 19:31:24 发布
本文介绍了一个使用管道(pipe)进行父子进程间通信的C语言程序实例。通过创建管道和调用fork()函数,父进程将字符串数据写入管道,而子进程从管道中读取并打印数据,展示了进程间通信的基本原理。


8471

被折叠的 条评论
为什么被折叠?



