IPC-PIPE管道-pipe-read/write-wait

概念


管道读写特点

管道的局限性

创建管道函数pipe

读写管道函数read/write

等待子进程中断或结束的函数wait

使用管道的特殊情况

创建无名管道

/*
创建无名管道,创建子进程
*/
void pipe_func(void)
{
int res;
int num;
pid_t pid;
int pipe_fd[2];
char r_buf[100], w_buf[100];
memset(r_buf, 0, sizeof(r_buf));
memset(w_buf, 0, sizeof(w_buf));
// 创建管道
if (pipe(pipe_fd) < 0)
{
perror("pipe error");
exit(EXIT_FAILURE);
}
// 创建子进程
res = fork();
if (res < 0)
{
perror("fork error");
exit(EXIT_FAILURE);
}
else if (res == 0)
{ // 子进程关闭写
close(pipe_fd[1]);
if ((num = read(pipe_fd[0], r_buf, sizeof(r_buf))) > 0)
{
printf("child fork read from pipe %d types, string is %s\n", num, r_buf);
}
close(pipe_fd[0]);
exit(EXIT_SUCCESS);
}
else
{ // 父进程关闭读
close(pipe_fd[0]);
printf("Please inpur str:");
scanf("%s", w_buf);
if ((num = write(pipe_fd[1], w_buf, strlen(w_buf)) != -1))
{
printf("prent fork write to pipe %d types, string is %s\n", num, w_buf);
}
waitpid(res, NULL, 0);
exit(EXIT_SUCCESS);
}
}
posted @   steve的miao  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示