进程间通信
#include <unistd.h>
int pipe(int pipefd[2]);
功能:创建一个匿名管道,用于进程间通信
参数:
-int pipefd[2]:传出参数
pipefd[0]对应的是管道的读端
pipefd[0]对应的是管道的写端
返回值:
成功返回0,失败返回-1
管道默认是阻塞的,如果管道中没有数据,read阻塞,如果管道满了,write阻塞
注意:匿名管道只能用于具有关系的进程之间的通信(父子进程、兄弟进程)
1.子进程写数据,父进程读数据并输出
//子进程发送数据给父进程,父进程读取到数据输出
#include <unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main() {
//在fork之前创建管道
int pipefd[2];
int ret = pipe(pipefd);
if(ret == -1) {
perror("pipe");
exit(0);
}
//创建子进程
pid_t pid = fork();
if(pid > 0) {
//父进程
//从管道读取端读取数据
char buf[1024] = {0};
int len = read(pipefd[0], buf, sizeof(buf));
printf("parent recv : %s, pid: %dn", buf, getpid());
} else if(pid == 0){
//子进程
//在管道中写入数据
char * str = "hello, i am child";
write(pipefd[1], str, strlen(str));
}
return 0;
}
2.子进程持续写数据,父进程持续接收
//子进程发送数据给父进程,父进程读取到数据输出
#include <unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main() {
//在fork之前创建管道
int pipefd[2];
int ret = pipe(pipefd);
if(ret == -1) {
perror("pipe");
exit(0);
}
//创建子进程
pid_t pid = fork();
if(pid > 0) {
//父进程
//从管道读取端读取数据
printf("i am parent process, pid: %dn", getpid());
char buf[1024] = {0};
while(1) {
int len = read(pipefd[0], buf, sizeof(buf));
printf("parent recv : %s, pid: %dn", buf, getpid());
}
} else if(pid == 0){
//子进程
printf("i am child process, pid: %dn", getpid());
while(1) {
//在管道中写入数据
char * str = "hello, i am child";
write(pipefd[1], str, strlen(str));
sleep(1);
}
}
return 0;
}
3.父子进程都能读和写数据
//子进程发送数据给父进程,父进程读取到数据输出
#include <unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main() {
//在fork之前创建管道
int pipefd[2];
int ret = pipe(pipefd);
if(ret == -1) {
perror("pipe");
exit(0);
}
//创建子进程
pid_t pid = fork();
if(pid > 0) {
//父进程
//从管道读取端读取数据
printf("i am parent process, pid: %dn", getpid());
char buf[1024] = {0};
while(1) {
//在管道中读取数据
int len = read(pipefd[0], buf, sizeof(buf));
printf("parent recv : %s, pid: %dn", buf, getpid());
//在管道中写入数据
char * str = "hello, i am parent";
write(pipefd[1], str, strlen(str));
sleep(1);
}
} else if(pid == 0){
//子进程
printf("i am child process, pid: %dn", getpid());
char buf[1024] = {0};
while(1) {
//在管道中写入数据
char * str = "hello, i am child";
write(pipefd[1], str, strlen(str));
sleep(1);
//在管道中读取数据
int len = read(pipefd[0], buf, sizeof(buf));
printf("child recv : %s, pid: %dn", buf, getpid());
}
}
return 0;
}
4.查看管道缓冲大小
#include <unistd.h>
#include<sys/types.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
int main() {
int pipefd[2];
int ret = pipe(pipefd);
//获取管道大小
long size = fpathconf(pipefd[0], _PC_PIPE_BUF);
printf("pipe size: %ldn", size);
return 0;
}