无名管道
无名管道怎么用呢?和操作文件差不多。
#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*