Linux进程间通信学习(20200128)

 

无名管道

无名管道怎么用呢?和操作文件差不多。

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <dirent.h>
#include <pwd.h>
#include <sys/wait.h>

int main(int arg, char * args[])
{
	
	int fd[2];//管道描述符
	char buf[100];//存放管道数据的
	int len;//记录长度
	pipe(fd);
	memset(buf, 0, sizeof(buf));
	int pid = fork();
	if (pid == 0)
	{
		close(fd[1]);//关闭第二个管道
		while((len = read(fd[0], buf, sizeof(buf))) >0)
		{
			write(STDOUT_FILENO, buf, len);
		}
		close(fd[0]);
	}
	else
	{
		close(fd[0]);//关闭第一个管道  2管道是写
		strcpy(buf, "hello world\n");
		write(fd[1], buf, sizeof(buf));
		close(fd[1]);
		waitpid(pid, NULL, 0);//等待子线程结束
	}
	return 0;
}

 

有名管道

创建一个管道文件

[root123@localhost myhome]$ mkfifo fifo1
[root123@localhost myhome]$ ls -l
prw-rw-r--. 1 root123 root123    0 Jan 28 06:21 fifo1

cat < fifo1。
通过cat命令从fifo1中读取数据。
ls > fifo1。
将ls命令输出的结果写入fifo1中

如何在代码中创建FIFO呢?

int mkfifo(const char *pathname, mode_t mode)
函数执行成功返回0,否则返回-1,并设置变量errno。
 

int main(int arg, char *args[])
{
	mkfifo("fifo1", 0666);//代表读写权限为rw-rw-rw-
	return 0;
}

删除fifo。
int unlink(const char *pathname);
函数执行成功返回0,否则返回-1,并设置变量errno。

如何读写FIFO 如何读写FIFO和文件操作相同

读FIFO例子

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <dirent.h>
#include <pwd.h>
#include <sys/wait.h>

//读取fifo中的内容
int main(int arg, char * args[])
{
	int len = 0;
	char buf[100];
	memset(buf, 0, sizeof(buf));
	int fd = open("fifo1", O_RDONLY);
	while((len = read(fd, buf, sizeof(buf))) > 0 )
	{
		printf("%s\n",buf);
	}
	close(fd);
	return 0;
}


写fifo中的内容

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <dirent.h>

int main(int arg, char *args[])
{
	
	char buf[100];
	memset(buf, 0, sizeof(buf));
	int fd = open("fifo1", O_WRONLY);
	while(1)
	{
		scanf("%s", buf);
		if(buf[0] == '0')
			break;
		write(fd, buf , sizeof(buf));
	}
		
	return 0;
	
	
}

 

编写同时编译两个的makefile文件

.SUFFIXES: .c .o

CC=gcc

SRCS1=test1.c
SRCS2=test2.c

OBJS1=$(SRCS1:.c=.o)
OBJS2=$(SRCS2:.c=.o)

EXE1=test1
EXE2=test2

all: $(OBJS1) $(OBJS2)
	$(CC) -o $(EXE1) $(OBJS1)
	$(CC) -o $(EXE2) $(OBJS2)
	@echo '^_^ ^_^ ^_^ ^_^ ^_^ ^_^ OK ^_^ ^_^ ^_^ ^_^ ^_^ ^_^'

.c.o: 
	$(CC) -Wall -g -o $@ -c $<

clean:
	-rm -f $(OBJS)
	-rm -f core*

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值