1.程间通信目的
2.匿名管道
1.原理
那如果以该进程为父进程创建子进程会是什么样的?
那父子进程如何完成通信呢?
补充:关于重定向 >
2.pipe()系统调用
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
int main()
{
// 1.创建管道
int fd[2] = {0};
int n = pipe(fd);
if (n == -1)
{
std::cerr << "pipe error" << std::endl;
return -1;
}
// 2.创建子进程
pid_t id = fork();
if (id < 0)
{
std::cerr << "fork error" << std::endl;
return -2;
}
if (id == 0)
{
int count = 0;
// 子进程 关闭读端
close(fd[0]);
while (1)
{
close(fd[0]);
std::string message = "hello ";
message += std::to_string(getpid());
message += ",";
message += std::to_string(count++);
// 写入管道
int n = write(fd[1], message.c_str(), message.size());
sleep(2);
}
exit(0);
}
else
{
char buff[1024];
// 父进程 关闭写端
close(fd[1]);
// 从管道中读
while (1)
{
int n = read(fd[0], buff, 1024);
if (n > 0)
{
// 读到数据
buff[n] = '\0'; // 系统字符串没有规定以0结尾
std::cout << "子进程->父进程 message:" << buff << std::endl;
}
else if (n == 0)
{
// 写端关闭 读到结尾
break;
}
}
int status;
pid_t rid = waitpid(id, &status, 0);
if (rid == -1)
{
std::cerr << "waitpid error" << std::endl;
return -3;
}
//int 16字节 前7位退出信号 后8位退出码
std::cout<<"子进程pid"<<rid<<"退出码"<<((status<<8)&0xFF)
<<"退出信号"<<(status&0x7F);
}
return 0;
}
3.匿名管道的四种情况
1.管道为空&&管道正常 read会阻塞
2.管道为满&&管道正常 wirte会阻塞
3.管道写端关闭,读端继续。读端读到0,表示读到文件结尾。
4.写端正常,读端关闭。OS会直接杀死进程