进程间通信(1)-有名管道

1)进程间通信的方式: 管道(有名)
2)有名管道的通信原理:通过在内存上开辟一块全新的空间,两个相互独立的进程通过文件描述符操纵这块独立的空间
3)使用对象:相互独立的 进程
4)创建函数:mkfifo命令 mkfifo(),
5)使用的函数 :
1.打开管道文件
int open(char *filename ,int oflag)//返回文件标识符filedes
filename 管道文件名
oflag O_RDONLY只读 ,O_WDONLY只写, O_RDWR 读写
2.关闭管道文件
int close(int filedes)
3.读管道文件
ssize_t read (int filedes, void *buf(n个字节拷到buff), size_t n,)
4.在管道文件中写东西
ssize_t write(int filedes,void *buf,size_t n)
6)管道文件的操作特点
1 .如果一个进程以只写打开管道,但是没有以只读或读写打开这个管道的进程,则这个操作会堵塞,直到有进程以读或读写打开,open才会返回
2 .如果一个进程以只读打开管道,但是没有只写或读写打开这个管道的进程,则这个操作会堵塞,直到有进程以只写或读写打开,open才会返回
3.当写端没有写入数据时,读端数据就会堵塞read调用,直到有写端写入或者写端不写
4.当管道没有空间时,再写入数据就会堵塞,直到有进程读数据,或者读端不读

// 在第一个进程中获取用户输入的字符,在第二个进程中统计用户输入的字符个数并输出
#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
void main()
{
   int a=open("FIFO","O_WRONLY");
   assert(a!=-1);
   printf("input data :\n");
   fflush(stdout);
   char c[128]={0};
   scanf("%s",c);
   int b=write(a,c,strlen(c));
   assert(b!=-1);
   close(a);
}

#include<stdio.h>
#include<assert.h>
#include<unistd.h>
#include<fcntl.h>
#include<string.h>
void main()
{
   int a=open("FIFO","O_RDONLY");
   assert(a!=-1);
   printf("open success");
   char b[128]={0};
   read(a,b,128);
   printf("\ncount=%d\n",strlen(b));
}




猜你喜欢

转载自blog.csdn.net/s_yj_q/article/details/78144579
今日推荐