2016-12-15 39 views
0

我在ubuntu上编写了一个c程序,该程序在fifo管道中写入和读取。我已经完成了编写程序的工作,现在我有一个循环读取问题。如何循环FIFO读取器程序C

我的阅读计划:

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

#define MAX_CTRLS 80 

void main() 
{ 
printf("test1"); 
    char ch2[MAX_CTRLS]; 
    int pipe1; 
    pipe1 = open("/tmp/ctrl", O_RDONLY); 
printf("test2"); 
    read(pipe1, ch2, MAX_CTRLS); 
    printf("%s",ch2); 
    close(pipe1); 
} 

这个程序应该在FIFO读,其存储在CH2然后CH2打印。但是,当它正常运行时,它可以完美运行,而在循环中运行它时,它什么都不会做。

这里是写程序1:

void send(char ch2[MAX_CTRLS]) 
{ 
    int create; 
    create = mkfifo("/tmp/ctrl", 0666); 
    int pipe1; 
    pipe1 = open("/tmp/ctrl", O_WRONLY); 
    write(pipe1, ch2, MAX_CTRLS); 
    close(pipe1); 
} 

这一个工程使用其他程序我有,人有这样一行:

ch2[0] = 'a'; 
printf("%s",ch2); 
send(ch2); 

的printf的帮助我确认CH2设置正确。我需要读取程序来循环读取功能,也就是每次在ch2中设置时打印。

我只是蚂蚁它打印一个在这种情况下,每次我的程序启动发送(ch2)。

Thaks提前

+0

什么是 “在一个循环中运行它” 是什么意思?我没有看到任何循环。 – unwind

+0

我们需要更多的信息。但看起来,如果没有任何可读的内容,则读取将在循环中被阻塞。 'select()'会成为你的朋友。 – Holger

+0

我想添加一段时间(1)在循环中运行阅读程序。 –

回答

0

我想你想有一个循环,打开管道和读取如果有的话是存在的,没有延迟,然后进入睡眠状态下一次读之前一段时间。 建议这样的事情,U还可以用于交换(;;),同时(boolValue ==真)

int fd = -1, naptime = 200; // 200msec 

for (;;){ fd = open(pipe, mode|nodelay); if (fd != -1){ int st = read (fd, buf, sizeof(buf)); /* open OK */ // do your printing of data if any exist - st holds read chars if(st >0) printf(buf); } sleep(naptime); // sleep til next reading }