使用read从fifo文件中获取未知长度的字符串

问题描述

我正在编写一个程序,该程序包含两个通过fifo进行通信的进程。 “写入器”进程在fifo文件中发送“读取器”进程需要读取并放入日志文件通知。棘手的是通知的长度是可变的。假设我阅读的长度为“ 200”,那么这可能在fifo中包含两条消息。但是,由于它们是两条消息,因此第二条消息将在第一条消息的\ n之后被截断,并且不会放入日志文件中。

逻辑解决方案是从fifo一项开始读取并将类似的字符打印到日志文件中:

void logging(){
    int logfifo_descriptor;
    char * logfifo_path = "/home/jens/Desktop/CLion_projects/Labo9/logfifo";
    mkfifo(logfifo_path,0666);
    char bufftemp[1];

    FILE *logfile;
    logfifo_descriptor = open(logfifo_path,O_RDONLY);
    while(1) {
        int check = read(logfifo_descriptor,bufftemp,1);

        if(check != 0) {
            logfile = fopen("gateway.log","a+"); // a+ (create + append) option will allow appending which is useful in a log file
            if (logfile == NULL){
                printf("Probleem met schrijven naar log file\n ");
            }
            fprintf(logfile,"%s",bufftemp);
            fclose(logfile);
        }
    }
    close(logfifo_descriptor);
}

但是,我可以想象这会导致while循环中大量循环。 (尽管我认为这不是一个很大的问题,因为它是子进程)。

这是日志文件现在的外观:(当读取长度为1时)

enter image description here

如果我阅读长度为200的内容,那么第二条消息将完全消失(因为在第一条消息之后很快就会消失)。如果我使用的长度为5,则第二条消息的前几个字符将消失。由于fifo的全部目的是让进程进行通信,因此听起来似乎不是写过程的一种选择,就是让阅读过程知道要写的消息有多长时间。

我的问题是:阅读功能是否有办法知道在哪里停止并为下一条消息再次循环? (也许会停在\ n?)

(应该有用,这是写程序的代码:)

void write_to_fifo(char * message,int sequence_number){

    char * string_to_write;
    time_t huidige_tijd = time(NULL);

    int length3;
    length3 = snprintf(NULL,"%d. %ld %s",sequence_number,huidige_tijd,message);
    string_to_write = malloc(length3);
    snprintf(string_to_write,length3,message);

    char * addition = "\n";
    strcat(string_to_write,"\n");

    pthread_mutex_lock(&lock_fifo);
    write(fifo_filedescriptor,string_to_write,strlen(string_to_write)+1);
    pthread_mutex_unlock(&lock_fifo);

    printf("%s",string_to_write);

    free(string_to_write);
} 

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)