管道学习

无名管道
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值