mkfifo创建有名管道
写程序(将文件test1的内容都读取到管道)
#include
#include
#include
#include
#include
#include
#include
#include
#define name "FIFO"
int atomic(int from, int to, int print);
int main() {
int fd_test, fd_pipe;
if (access(name, F_OK) == -1) {
if ((mkfifo(name, 0777) != -1) && (errno == EEXIST)) {
printf("Create fifo pipe failure\n");
exit(0);
}
}
if ((fd_test = open("test1", O_RDWR | O_CREAT, 0777)) < 0) {
printf("Open or Create test1 failure\n");
exit(0);
}
printf("Open test1 result %d\n", fd_test);
if ((fd_pipe = open(name, O_RDWR)) < 0) {
printf("Open fifopipe failure\n");
exit(-1);
}
printf("Open pipe result %d\n", fd_pipe);
atomic(fd_test, fd_pipe, 1);
close(fd_pipe);
close(fd_test);
return 0;
}
int atomic(int from, int to, int print) {
int time = 0;
int size;
char buf[PIPE_BUF];
size = read(from, buf, PIPE_BUF);
for (; size > 0;) {
if (size >= PIPE_BUF) {
write(to, buf, PIPE_BUF);
} else {
write(to, buf, size);
}
if (print > 0) {
printf("test1 content is \n%s", buf);
}
memset(buf, 0, strlen(buf));
size = read(from, buf, PIPE_BUF);
}
return time;
}
读程序(将管道中的数据写入文件test2)
#include
#include
#include
#include
#include
#include
#include
#include
#define name "FIFO"
int atomic(int from, int to, int print);
int main() {
int fd_test, fd_pipe;
if (access(name, F_OK) == -1) {
if ((mkfifo(name, 0777) != -1) && (errno == EEXIST)) {
printf("Create fifo pipe failure\n");
exit(0);
}
}
if ((fd_test = open("test2", O_WRONLY | O_CREAT, 0777)) < 0) {
printf("Open or Create test2 failure\n");
exit(0);
}
printf("Open test2 result %d\n", fd_test);
if ((fd_pipe = open(name, O_RDONLY)) < 0) {
printf("Open fifopipe failure\n");
exit(-1);
}
printf("Open pipe result %d\n", fd_pipe);
atomic(fd_pipe, fd_test, 1);
close(fd_pipe);
close(fd_test);
unlink(name);
return 0;
}
int atomic(int from, int to, int print) {
int time = 0;
int size;
char buf[PIPE_BUF];
size = read(from, buf, PIPE_BUF);
for (; size > 0;) {
if (size >= PIPE_BUF) {
write(to, buf, PIPE_BUF);
} else {
write(to, buf, size);
}
if (print > 0) {
printf("test1 content is \n%s", buf);
}
memset(buf, 0, strlen(buf));
size = read(from, buf, PIPE_BUF);
}
return time;
}