我在ubuntu中编写了一个用于写入和读取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)。
事先提前
答案 0 :(得分:0)
我想你想要一个打开管道的循环并读取是否有任何东西,没有延迟,然后在下次阅读之前进入睡眠状态一段时间。 建议这样的事情,你也可以交换(;;)到while(boolValue == true)
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
}
答案 1 :(得分:0)
我需要读取程序来循环读取功能,也就是每次在ch2中设置时都打印。
仅添加 awhile(1)以便在循环上运行读取程序并不能解决问题,因为device register successfully device2
来自已关闭的FIFO(后一种情况) 编写程序的第一轮运行不会阻塞,而是返回0,我们当然不希望繁忙的read()
循环。因此,我们需要一种等待FIFO可读的方法。如果我们有幸可以运行Linux,则可以使用inotify
来获取有关写入FIFO的通知。阅读代码可能是:
read()