无名管道 :
1、创建一个管道的数组,1是发送,0是接收
2、使用pipe创建一个管道,如果返回值小于0,则是错误的
3、创建一个子进程
4、子进程和父进程利用write和read进行读写操作。
/**
无名管道 :
1、创建一个管道的数组,1是发送,0是接收
2、使用pipe创建一个管道,如果返回值小于0,则是错误的
3、创建一个子进程
4、子进程和父进程利用write和read进行读写操作。
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(){
//设置管道,1是发送,0是接收
int fd_pipe[2];
//设置将要发送的信息
char buff[] = "hello pipe";
//创建一个管道标志
pid_t pid;
//pipe创建一个管道
if(pipe(fd_pipe) < 0)
perror("pipe");
//创建一个子进程
pid = fork();
if(pid < 0){
perror("fork");
exit(-1);
}
//是子进程
if(pid == 0){
//利用管道,想里面传递消息,并且结束
write(fd_pipe[1],buff,strlen(buff));
_exit(0);
}
else{
wait(NULL);
//这个的意思是设定buff为空
memset(buff,0,sizeof(buff));
//设定为读取,将管道里面的数读出来。
read(fd_pipe[0],buff,sizeof(buff));
printf("buf=[%s]\n",buff);
}
return 0;
}
有名管道
创建一个有名管道,使用mkfifo
使用文件操作符进行打开
在进行读写
/*写入*/
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
int main(){
int fd;
int ret;
char send[100] = "Hello I love you";
//创建一个有名管道,属性是用户可读可写 ,代表的含义是 0600
ret = mkfifo("my_fifo",S_IRUSR|S_IWUSR);
if(ret != 0)
perror("makefifo");
printf("before open\n");
//对管道进行打开,可读可写模式
fd = open("my_fifo",O_WRONLY);
if(fd < 0)
perror("open fifo");
printf("after open and before read\n");
//对fd(有名管道)进行写入
write(fd,send,strlen(send));
printf("write to my_fifo buf = %s\n",send);
return 0;
}
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
int main(){
int fd;
int ret;
//创建接收的buf
char recv[100];
//创建一个管道,属性0600
ret = mkfifo("my_fifo",S_IRUSR|S_IWUSR);
if(ret != 0){
perror("mkfifo");
}
printf("befor open\n");
//使用文件操作符打开
fd = open("my_fifo",O_RDONLY);
if(fd < 0)
perror("open fifo");
printf("after open and before read\n");
//清空
bzero(recv,sizeof(recv));
//进行读操作
read(fd,recv,sizeof(recv));
printf("read from my_fifo buf = [%s]\n",recv);
return 0;
}