FIFO文件和读/写

4
我一直在尝试了解FIFO和这个底层I/O,在星期一之前的实验室之前,我遇到了一个我不太理解的情况。 程序应该: 服务器:
- 创建FIFOs, - 发送5条消息:"Message #i",每5秒发送一次, - 删除FIFOs,
客户端:
- 从FIFO读取并显示消息, - 如果没有消息,则在6秒内终止,
虽然它们确实在通信,但客户端显示的内容并不完全是我发送给它的内容,并且更重要的是,每次新消息到达时似乎都会从头开始读取。我已经尝试了相当长时间,它似乎与文档所说的不符...请帮帮我!:( 服务器
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>  
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int main(int argc, char* argv[])
{       
    int s2c, c2s, i; 
    char fifo_name1[] = "/tmp/fifo1";
    char fifo_name2[] = "/tmp/fifo2";
    char msg[80], buf[10];
    struct stat st;

    // if no fifos, create 'em
    if (stat(fifo_name1, &st) != 0)
        mkfifo(fifo_name1, 0666);
    if (stat(fifo_name2, &st) != 0)
        mkfifo(fifo_name2, 0666);

    s2c= open(fifo_name1, O_WRONLY);
    c2s= open(fifo_name2, O_RDONLY);

    // start sending messages, with 5s interval
    for (i=0; i<5; i++)
    {
        printf("Message #%d \n", i);

        strcat(msg, "Message #"); 
        strcat(msg, itoa(i, buf, 10));
        strcat(msg, "\0"); 

        write(s2c, msg, strlen(msg)+1);

        sleep(5);
    }

    // delete fifos
    unlink(fifo_name1);
    unlink(fifo_name2);
    printf("server exit successfully");
    return EXIT_SUCCESS;
}

客户端

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    int c2s, s2c, c=0;
    char buf[10];

    char fifo_name1[] = "/tmp/fifo1";
    char fifo_name2[] = "/tmp/fifo2";
    s2c= open(fifo_name1, O_RDONLY);
    c2s= open(fifo_name2, O_WRONLY);

    // receive messages
    while (1)
    {
        if (read(s2c, &buf, sizeof(char)*10) > 0)
        {
            printf("%s \n", buf);
            c=0;
        }
        sleep(1);
        c++;    
        if (c>6) 
            break;
    }

    printf("client exit successfully");
    return EXIT_SUCCESS;
}       
1个回答

4

strcat(msg, "Message #");总是将内容添加到已经存在于msg中的字符串的末尾,并且在循环期间不会重置该字符串。使用strcpy(msg, "Message #");替换它,以便可以从头开始每个新消息。


非常感谢,现在它可以工作了! :D 看起来我一直在错误的地方寻找错误,真是太丢人了 :( - Kreweta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接