..........................................pipe.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#if 0
//对于命名管道的操作与文件操作非常相似,对文件操作中使用的函数read(),write(),close()
//等函数都可以是用来对管道进行操作
//半双工管道的读写---父子进程间的通信
int main()
{
pid_t pid; //创建进程号的类型定义:pid_t 实际上就是int类型的
int fd[2];
int res = pipe(fd);//必须在系统调用fork()之前调用pipe(),
if(res == -1)
{
printf("create pipe error.\n");
exit(1);
}
pid = fork();
if(pid == 0) //子进程从管道中获取数据
{
char buf[256];
close(fd[1]); //fd[1](管道写端)写数据
read(fd[0],buf,256);
printf("From Parent Msg:>%s\n",buf);
close(fd[0]);
}
else if(pid>0) //父进程向管道中写数据
{
char *msg = "Good Good Study,Day Day up.";
close(fd[0]); //fd[0](管道读端)读数据
write(fd[1],msg,strlen(msg)+1); //strlen求得字符串世纪长度
close(fd[1]);
int status;
wait(&status);
}
else
{
exit(1);
}
return 0;
}
#endif
进程间通信--管道(半双工)
最新推荐文章于 2021-07-02 13:25:44 发布