当前位置: 技术问答>linux和unix
请教通过fifo管道写,读数据问题
来源: 互联网 发布时间:2016-11-10
本文导语: 本帖最后由 qiuchuan119 于 2011-02-28 23:50:17 编辑 首先是通过管道在一个while(1)里面写数据,等待read端的关闭(接受到SIGPIPE)信号时 #include #include #include #include #include #include #include #include #include...
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF
#define TEN_MEG (1024 * 1024 * 10)
void mypipe(int sig)
{
printf("the read file is closedn");
}
int main()
{
int pipe_fd;
int res;
int open_mode = O_WRONLY;
int bytes_sent = 0;
char buffer[BUFFER_SIZE + 1];
(void) signal(SIGPIPE,mypipe);
if (access(FIFO_NAME, F_OK) == -1) {
res = mkfifo(FIFO_NAME, 0777);
if (res != 0) {
fprintf(stderr, "Could not create fifo %sn", FIFO_NAME);
exit(EXIT_FAILURE);
}
}
printf("Process %d opening FIFO O_WRONLYn", getpid());
pipe_fd = open(FIFO_NAME, open_mode);
printf("Process %d result %dn", getpid(), pipe_fd);
if (pipe_fd != -1) {
while(1) {
res = write(pipe_fd, buffer, BUFFER_SIZE);
if (res == -1) {
fprintf(stderr, "Write error on pipen");
exit(EXIT_FAILURE);
}
bytes_sent += res;
printf("fifo have writed %d datan",bytes_sent);
}
(void)close(pipe_fd);
}
else {
exit(EXIT_FAILURE);
}
printf("Process %d finishedn", getpid());
exit(EXIT_SUCCESS);
下面是read端的代码,统计一共读了多少数据
#include
#include
#include
#include
#include
#include
#include
#include
#define FIFO_NAME "/tmp/my_fifo"
#define BUFFER_SIZE PIPE_BUF
int main()
{
int pipe_fd;
int res;
int open_mode = O_RDONLY;
char buffer[BUFFER_SIZE + 1];
int bytes_read = 0;
memset(buffer, '', sizeof(buffer));
printf("Process %d opening FIFO O_RDONLYn", getpid());
pipe_fd = open(FIFO_NAME, open_mode);
printf("Process %d result %dn", getpid(), pipe_fd);
if (pipe_fd != -1) {
do {
res = read(pipe_fd, buffer, BUFFER_SIZE);
bytes_read += res;
} while (bytes_read