如何使用管道实现两个进程间的通信:
步骤:
1、父进程创建管道
2、父进程创建子进程(子进程继承了父进程的文件描述符号)
3、考虑父进程负责的工作(这里设置为写)
a、关闭读端
b、通过管道的写端文件描述符,写数据到管道空间
c、阻塞等待子进程的结束,子进程结束的时候,收尸
4、考虑子进程负责的工作
a、关闭写端
b、从管道中读取数据
c、将读取到的数据显示到显示器
d、结束进程
举例:(pipe.c)
程序:
#include <stdio.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(
void) {
int fd[
2];
int pc = pipe(fd);
char buf[
128];
int r;
char *msg =
"this is a test\n";
if(pc == -
1) {
perror(
"pipe");
return -
1;
}
pid_t pid = fork();
if(pid == -
1) {
perror(
"fock");
return -
1;
}
if(pid ==
0) {
close(fd[
1]);
r = read(fd[
0], buf,
128);
write(
1, buf, r);
exit(
0);
}
else {
close(fd[
0]);
write(fd[
1], msg,
strlen(msg));
wait(NULL);
}
return 0;
}
运行:
命令: tarena@ubuntu:~/day/day32$ a.out
结果:
this is a test