我想在 C 中不断读取 fifo 管道。 我的代码示例有效,但由于我使用 while(1),我的一个 CPU 核心始终处于 100%。
所以我的问题是:有没有一种更流畅的方法来读取 fifo,而不用杀死 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;
}
最佳答案
您有 3 种方法来处理它:-
从 FIFO 读取时可以使用阻塞模式。
最简单的方法是在 while 循环中使用 sleep() 来暂停线程一段时间,这会暂时减少 cpu 负载。
您可以使用信号和中断,写入器可以在向 FIFO 写入数据时发送信号。读取器可以暂停,直到从 FIFO 写入器接收到信号并执行读取操作,直到 FIFO 结束,并且再次暂停。
关于c - 如何用C不断读取FIFO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27445172/