如何不断地用C读FIFO [英] How to constantly read FIFO in C
问题描述
我想在C持续读一个FIFO管道
我的code例如工作,但由于我使用一段时间(1)我的CPU核心之一是100%所有的时间。
所以我的问题:是否有读取FIFO平滑的方式,而不杀死CPU
的#include<&stdio.h中GT;
#包括LT&;&string.h中GT;
#包括LT&;&fcntl.h GT;
#包括LT&;&stdlib.h中GT;
#包括LT&;&unistd.h中GT;
#包括LT&;&stdbool.h GT;布尔后缀(字符*基地,字符* STR){
INT BLEN = strlen的(基地);
INT SLEN = strlen的(STR);
回报(BLEN> = SLEN)及和放大器; (0 == STRCMP(基地+ BLEN - SLEN,STR));
}布尔preFIX(为const char * pre,为const char *海峡)
{
返回STRNCMP(pre,STR,strlen的(pre))== 0;
}
空格格(字符* S){
而(* S&放大器;&安培;!* S ='\\ n'和;&安培;!* S ='\\ r')■++;
* S = 0;
}INT主(INT ARGC,CHAR *的argv [])
{
INT FIFO,C = 0;
焦炭BUF [200]; 烧焦fifo_name [] =/var/log/proftpd_log_all.fifo;
FIFO =开(fifo_name,O_RDONLY | O_NONBLOCK); 而(1)
{
如果(读(FIFO,&安培; BUF,sizeof的(字符)* 200)0)
{
如果(preFIX([STOR],BUF)){
//的printf(%S \\ n,BUF);
如果(的strstr(BUF,.jpf)!= NULL){
// ...
}
}
}
}
的printf(退出);
关闭(FIFO);
返回0;
}
您必须对其进行处理3种方法: -
-
您可以使用阻塞模式,而从FIFO读取。
-
最简单的方法是使用睡眠()while循环内挂起线程了一段时间,这将减少CPU负载瞬间。
-
您可以使用信号放大器&;中断,每当它写入,直到一个信号被从FIFO&放大器的作家接收东西FIFO.The读者可悬浮作家可以发送一个信号;执行读取操作,直到FIFO的结束,并再次暂停。
I want to read a fifo pipe constantly in C. My code example works, but since i use while(1) one of my CPU cores is at 100% all the time.
So my question: Is there a smoother way to read the fifo, without killing the CPU?
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
bool suffix (char* base, char* str) {
int blen = strlen(base);
int slen = strlen(str);
return (blen >= slen) && (0 == strcmp(base + blen - slen, str));
}
bool prefix(const char *pre, const char *str)
{
return strncmp(pre, str, strlen(pre)) == 0;
}
void chomp(char *s) {
while(*s && *s != '\n' && *s != '\r') s++;
*s = 0;
}
int main(int argc, char *argv[])
{
int fifo, c=0;
char buf[200];
char fifo_name[] = "/var/log/proftpd_log_all.fifo";
fifo = open(fifo_name, O_RDONLY|O_NONBLOCK);
while (1)
{
if (read(fifo, &buf, sizeof(char)*200) > 0)
{
if (prefix("[STOR]",buf)) {
//printf("%s \n", buf);
if (strstr(buf, ".jpf") != NULL) {
//...
}
}
}
}
printf("exit");
close(fifo);
return 0;
}
You have 3 methods for handling it:-
You can use Blocking mode while reading from FIFO.
Simplest method is to use sleep() within the while loop to suspend the thread for sometime , this would reduce cpu load momentarily.
You can use signals & interrupts,writer can send a signal whenever it writes something to FIFO.The reader can be suspended until a signal is received from the writer of FIFO & performs the read operation until end of FIFO and suspends again.
这篇关于如何不断地用C读FIFO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!