【 实验目的】 】
1、掌握有名管道的创建和读写方式
2、熟悉 UNIX/LINUX 支持的有名管道通信方式
【 【 实验内容】 】
1. 创建有名管道;
2. 本进程执行循环等待数据被写入到管道中并读有名管道;
3. 打开有名管道并写数据到名管道;
参考代码:
//read_fifo.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#define BUFFER_SIZE 1024
int main(int argc, char **argv)
{
int fd;
if (argc < 2)
{
fprintf(stdout, "Usage: %s <filename>\n", argv[0]);
exit(1);
}
//int open(const char *path, int oflag, ...);
if ((fd = open(argv[1], O_RDONLY)) < 0)
{
fprintf(stderr, "open fifo %s for reading failed: %s\n", argv[1], strerror(errno));
exit(1);
}
fprintf(stdout, "open fifo %s for reading successed.\n", argv[0]);
char buffer[BUFFER_SIZE];
ssize_t n;
while (1)
{
again:
//ssize_t read(int fd, void *buf, size_t count);
if ((n = read(fd, buffer, BUFFER_SIZE)) < 0)
{
if (errno == EINTR)
{
goto again;
}
else
{
fprintf(stderr, "read failed on %s: %s\n", argv[1], strerror(errno));
exit(1);
}
}
else if (n == 0)
{
fprintf(stderr, "peer closed fifo.\n");
break;
}
else
{
buffer[n] = '\0';
fprintf(stdout, "read %d bytes from fifo: %s\n", n, buffer);
}
}
return 0;
}
// write_fifo.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#define BUFFER_SIZE 1024
void signal_handler(int s);
int main(int argc, char **argv)
{
int fd;
if (argc < 2)
{
fprintf(stdout, "Usage: %s <filename>\n", argv[0]);
Linux 系统实验手册
3
exit(1);
}
signal(SIGPIPE, signal_handler);
//int open(const char *path, int oflag, ...);
if ((fd = open(argv[1], O_WRONLY)) < 0)
{
fprintf(stderr, "open fifo %s for writting failed: %s\n", argv[1], strerror(errno));
exit(1);
}
fprintf(stdout, "open fifo %s for writting successed.\n", argv[0]);
char buffer[BUFFER_SIZE];
ssize_t n;
//char *fgets(char *s, int size, FILE * stream);
while (fgets(buffer, BUFFER_SIZE, stdin))
{
again:
//ssize_t write(int fd, const void *buf, size_t count);
if ((n = write(fd, buffer, strlen(buffer))) < 0)
{
if (errno == EINTR)
{
goto again;
}
else
{
fprintf(stderr, "write() failed on fifo: %s\n", strerror(errno));
break;
}
} // end if
} // end while
return 0;
}
void signal_handler(int signo)
{
fprintf(stdout, "Caught signal %d\n", signo);
}
// create_fifo.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>
int main(int argc, char **argv)
{
if (argc < 2)
{
fprintf(stdout, "Usage: %s <filename>\n", argv[0]);
exit(1);
}
//int mkfifo(const char *path, mode_t mode);
if (mkfifo(argv[1], 0644) < 0)
{
fprintf(stderr, "mkfifo() failed: %s\n", strerror(errno));
exit(1);
}
return 0;
}