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); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)