进程通信 管道通信

来源:互联网 发布:空白头像软件下载 编辑:程序博客网 时间:2024/05/01 22:23
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>

void read_from_pipe(int fd)
{
char buf[100];
read(fd,buf,100);
printf("read from pipe: %s\n",buf);
}
void write_to_pipe(int fd)
{
char *buf="hello pipe!";
write(fd,buf,strlen(buf)+1);
printf("write into pipe: %s\n",buf);
}
int main()
{
pid_t pid,pr;
int fd[2];
int stat;
if(pipe(fd)){

printf("pipe failed!\n");
exit(0);
}
pid=fork();
switch(pid){

case -1:
printf("fork failed\n");
exit(0);
case 0:
close(fd[1]);
read_from_pipe(fd[0]);
exit(0);
default:
close(fd[0]);
write_to_pipe(fd[1]);
pr = wait(&stat);
exit(0);
}
return 0;

}

运行结果:


0 0
原创粉丝点击