for printf */
#include <stdio.h>
/* for fork pipe close write read */
#include <unistd.h>
/* for exit */
#include <stdlib.h>
#define MAX_STRING 1024
int main(int argc, char *argv[])
{
/* 参考pipe函数原型
* pipefd[0] 代表读端.
* pipefd[1] 代表写端 */
int pipefd[2];
/* 参考fork函数原型 */
pid_t pid;
/* 读取数据存放在buf中 */
char buf[MAX_STRING] = {0};
/* 如果pipe打开失败,打印信息,并退出 */
if (pipe(pipefd) != 0) {
printf("pipe eorror!\n");
exit(EXIT_FAILURE);
}
/* fork子进程 */
/* 管道只能在具有共同祖先的进程间使用*/
pid = fork();
/* 子进程处理 */
if (pid == 0) {
/* 关闭读端 */
/* 管道只能工作在半双工模式下,也即数据只能单向流动*/
close(pipefd[0]);
/* 在写端写数据 */
write(pipefd[1], "hello", 5);
/* 数据写完关闭 */
close(pipefd[1]);
/* 子进程成功退出 */
exit(EXIT_SUCCESS);
}
/* 父进程关闭写端 */
close(pipefd[1]);
/* 父进程读取内容到buf中 */
read(pipefd[0], buf, MAX_STRING);
/* 打印读取到的内容 */
printf("buf:%s\n", buf);
/* 返回 */
return 0;
}
08-20
1082

01-10