目录
管道读写规则
1.写入时候
(1)有读端存在时候,写端管道空间写入数据,管道满容量为65536(unsigned short 为65535),写管道阻塞;
(2)读端不存在时候,写端管道无意义,会发送SIGPIPE信号干掉管道进程。
2.读入时候
(1)有写端存在时候:
①管道中数据 >= 要求读取数据,读出要求数据;
②管道中数据 < 要求读取数据,读出管道中实际数据;
③管道无数据,阻塞;
(2)无写端存在时候:管道中有数据就读取数据,没有数据就返回0;
注意:使用管道时候,读端管道先关写端;写端管道先关读端;
无名管道(pipe)
1.父写子读,父进程关闭读取文字描述符,子进程关闭写入文件描述符;
2.多用于亲缘关系进程间的通信;
3.可用于任何同主机进程间的通信(单向);
4.使用pipe函数创建一个文件描述符数组——存取两个文件描述符,
int fd[2];
if (pipe(fd) < 0)
{
perror("Fail to pipe");
return -1;
}
无名管道代码例写
1.自读自写
#include <stdio.h>
#include <unistd.h>
#include <string.h>
//自读自写
int main(int argc, const char *argv[])
{
int fd[2];
int n;
pid_t pid;
char *str = "I love China";
char buf[100]={0};
if(pipe(fd)<0)
{
perror("Fail to pipe");
return -1;
}
write(fd[1],str,strlen(str));
n = read(fd[0],buf,sizeof(buf));
printf("read %d bytes :%s\n",n,buf);
close(fd[0]);
close(fd[1]);
return 0;
}
2.创建两个线程,一个写入,一个读取;
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/wait.h>
//父写子读
void write_f(int fd)
{
char buf[1024] = {0};
int n;
while (1)
{
memset(buf,0,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
write(fd,buf,strlen(buf));
if(strncmp(buf,"quit",4) == 0)
{
break;
}
}
}
void read_f(int fd)
{
char buf[1024] = {0};
int n;
while(1)
{
memset(buf,0,sizeof(buf));
n = read(fd,buf,sizeof(buf));
printf("读了 %d 个字符,字符串为: \n%s\n",n-1,buf);
if(strncmp(buf,"quit",4) == 0)
{
break;
}
}
}
int main(int argc, const char *argv[])
{
int fd[2];
int n;
pid_t pid;
char *str = "I love China";
char buf[100]={0};
if(pipe(fd)<0)
{
perror("Fail to pipe");
return -1;
}
write(fd[1],str,strlen(str));
n = read(fd[0],buf,sizeof(buf));
pid = fork();
if (pid < 0)
{
perror("Fail to fork");
return -1;
}
else if (pid > 0)
{
close(fd[0]);
write_f(fd[1]);
wait(NULL);//Don't lose: recycle the chile
}
else if (pid == 0)
{
close(fd[1]);
read_f(fd[0]);
}
close(fd[0]);
close(fd[1]);
return 0;
}
本文详细介绍了无名管道(Pipe)的读写规则,包括当读写端存在与否时的行为,并提供了两个示例:一个是自读自写的简单应用,另一个涉及创建两个线程分别进行读写操作。强调了在使用管道时,应当遵循先关闭读端再关闭写端的原则,以及无名管道主要用于亲缘进程间的单向通信。
3574

被折叠的 条评论
为什么被折叠?



