[英]How to loop a FIFO reader program in C
我正在用ubuntu編寫ac程序,該程序在fifo管道中讀寫。 我已經使程序編寫完美地工作了,但是現在我在循環中遇到問題。
我的閱讀程序:
#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中設置時都打印。
在這種情況下,每次程序啟動send(ch2)時,我都只是將其打印出來。
提前解凍
我認為您希望有一個循環來打開管道並讀取是否有任何內容,沒有延遲,然后在下一次讀取之前進入睡眠狀態。 建議這樣,您也可以將(;;)換成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 }
我需要讀取程序來循環讀取功能,也就是每次在ch2中設置時都打印。
簡單地添加一個while(1)來在循環上運行讀取程序是行不通的,因為來自已關閉的FIFO的read()
(在第一次運行寫入程序后就是這種情況)不會阻塞,而是返回0,我們當然不希望忙碌的read()
循環。 因此,我們需要一種等待FIFO可讀的方法。 如果我們有幸可以運行Linux,則可以使用inotify
來通知有關寫入FIFO的信息。 閱讀代碼可以是:
#include <sys/inotify.h>
int fd = inotify_init();
inotify_add_watch(fd, "/tmp/ctrl", IN_MODIFY);
pipe1 = open("/tmp/ctrl", O_RDONLY);
struct inotify_event inev;
while (read(fd, &inev, sizeof inev))
if (read(pipe1, ch2, MAX_CTRLS) > 0)
printf("%s", ch2), fflush(stdout);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.