进程间通讯
无名管道
特点
1.只能用于具有血缘关系的进程间通信
2.单工的通信模式,具有固定的读端和写端
3.无名管道创建时会返回两个文件描述符,分别用于读写管道
无名管道的创建 pipe
管道代码:
#include <stdio.h>
#include <unistd.h>
int main(){
int pfd[2];
int re;
char buf[20];
pid_t pid;
re = pipe(pfd);
if(re < 0 ){
perror("pipe");
return 0 ;}
pid = fork();
if(pid<0){
perror("fork");
return 0;
}else if(pid==0){
close(pfd[1]);
while(1){
strcpy(buf,"hahhhahhah");
write(ptd[1],buf,strlen(buf));
sleep(1);
}}else{
close(pfd[0]);
while(1){
re = read(pfd[0],buf,20);
if(re > 0){
printf(""read pipe=%s\n",buf);}}
}
}
注意:
1.只能用于亲缘关系的进程间通信(父子进程,兄弟进程)
2.管道通讯时单工的,一端读,一端写(程序实现设计好)
3.数据自己读不能自己写
4.管道可以用于大于2个进程共享
有名管道
特点:
1.有名管道可以使非亲缘的两个进程互相通信
2.通过路径名来操作,在文件系统中可见,但内容存放在内存中
3.文件IO来操作有名管道
4.遵循先进先出规则
5.不支持leek操作
6.单工读写
创建:mkfifo
有名管道:
#include <stdlib.h>
int main() {
int re;
int fd;
char buf[32];
re = mkfifo("/myfifo",0666);
if(re<0){
perror(""mkfifo);
return 0;
}
fd = open("/myfifo",O_WRONLY);
if(fd<0)
{
perror("open");
return 0;}
while(1){
fgets(buf,32 stdin);
write(fd,buf,strlen(buf));
}
}
//
读
#include <stdlib.h>
int main() {
int re;
int fd;
char buf[32];
fd = open("/myfifo",O_WRONLY);
if(fd<0)
{
perror("open");
return 0;}
while(1){
read(fd,buf,32);
printf("read fifo=%s\n",buf);
}
}
管道进阶
#include <stdio.h>
#include <unistd.h>
int main(){
int pfd[2];
int re;
char buf[40];
pid_t pid;
re = pipe(pfd);
if(re < 0 ){
perror("pipe");
return 0 ;}
printf("%d,%d\n",pfd[0],pfd[1]);
for(int i=0;i<2;i++){
pid = fork();
if(pid<0){
perror("fork");
return 0;
}else if(pid > 0){
}else{
break;
}
}
if(i==2){
close(pfd[1]);
while(1){
re = read(pfd[0],buf,20);
if(re>0){
printf("%s\n",buf);
}
}
return 0;
}
if(i ==1){
close(pfd[0]);
while(1){
strcpy(buf,"this is 2 process");
write(pdf[1],buf,strlen(buf));
sleep(1);
}
return 0;
}
if(i==0)
{
close(pfd[0]);
while(1){
strcpy(buf,"this is 1 process");
write(pdf[1],buf,strlen(buf));
}
return 0;
}
}