LINUX系统编程-进程间通信(一)
一、无名命管道(Pipe)
1-1什么是管道?
管道是linux从Unix继承过来的一种较为原始的进程间的同行方式,是在具有亲属关系的进程间建立一个共享文件(伪文件)实际为一个环形消息队列,借用内核的缓冲区,使消息从进程一方流向另外一方的通信过程,这个共享文件就是管道,通信方式是半双工方式。
1-2管道API函数
1.close函数,用来关闭权限。
#include <unistd.h>
int close(int fd);
2.pipe函数,创建管道。
#include <unistd.h>
int pipe(int pipefd[2]);
//规定:fd[0] → 读; fd[1] → 写,就像0对应标准输入,1对应标准输出一样。向管道文件读写数据其实是在读写内核缓冲区。
那么我们怎么实现呢?首先我们先创立一个管道,然后再创立一个进程,通过文件的读和写操作实现在进程间通信。
1-3管道代码展示
// 无命名管道代码展示
#include<stdio.h>
#include<string.h>
#include<unistd.h>
int main()
{
int fd[2];
int pid;
char buff[53] ;
if(pipe(fd)==-1)
{
printf("pipe create failed!\n");
}
pid = fork();
if(pid>0)
{
printf("this is father\n");
close(fd[0]);//关闭读
write(fd[1],"this is father write!,strlen("this is father write!"));
wait();
}
else if(pid==0)
{
sleep(3);//先让子进程睡眠三秒,让父进程跑先写进一些内容,子进程才能读。
printf("this is child\n");
close(fd[1]);
read(fd[0],buff,1);
printf("the date from father:%s\n",buff);
}
return 0;
}
运行结果:
CLC@Embed_Learn:~$ ./pipe
this is father
this is child
the date from father:this is father write!
CLC@Embed_Learn:~$
二、名命管道(FIFO)
2-1什么是命名管道?
因为命名管道没有名称,只能在亲属进程间进行通信,所以有很大限制,所以我们需要用命名管道来摆脱这个窘境。
2-2API函数讲解
#include<sys/stat.h>
int mkfifo(const char *pathname,mode_t mode);
//参数一:文件名
//参数二:就是配置为只读/只写
2-3代码展示
//read jincheng
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<errno.h>
#include<stdio.h>
int main()
{
char buff[30];
if(mkfifo("./fife",0600)==-1&&errno!=EEXIST)
{
printf("failed!\n");
errno("why");
}
int fd = open("./fife",O_RDONLY);//写道这里是读不出来的,会发生堵塞
//因为还需要一个进程对文件进行写,才能边读。
printf("open sucess!\n");
//ssize_t read(int fd, void *buf, size_t count);
read(fd,buff,20);
iprintf("the data of fife:%s\n",buff);
close(fd);
return 0;
}
// wirte jincheng
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<errno.h>
#include<stdio.h>
#include<string.h>
int main()
{
char *str = "this is liushan";
int cnt = 0;
int fd = open("./fife",O_WRONLY);
while(1){
write("./fife",str,strlen(str));
printf("write suceess!\n");
cnt++;
if(cnt==5)
{
break;
}
}
close(fd);
return 0;
}
之后的内容见链接: LINUX进程间通信(二).以上为个人对进程间通信的看法,欢迎大家指正。