1

I am building a server that communicates through FIFO with it's clients.

So far I've managed to create a FIFO, run a new thread, once a message arrives in the FIFO and output the message from the thread.

The problem is that as soon as the client writes something in the pipe, the server just prints the message endlessly (I am reading from the pipe in a while(1)).

My question is: shouldn't the read operation also remove the message from the pipe, so it doesn't get read again? Isn't that the point of First In, First Out? Is that something I have to do manually?

Here's my code too, if that helps: http://pastebin.com/Ag7vgrav
What I do to write in the FIFO is just: echo test > /home/ubuntu/work/my_fifo

4

1 回答 1

5

您需要检查来自 的返回码read(2)。如果它返回-1,则发生错误,您应该立即停止阅读。如果它返回 0,那就是 EOF,这意味着写入器关闭了 FIFO 的末端,您也应该停止写入并关闭 FIFO 的末端。

为了支持多个客户端,每次接受新客户端时都需要重新打开 FIFO。

您在管理子线程的方式上也有一些未定义的行为。无法保证线程将在while循环的当前迭代结束之前启动main(),此时thread_arg实例超出范围。为了确保线程在数据仍然有效时仍然可以访问该数据,您需要将其设为全局数据(如果您只有一个子线程),或者在堆上动态分配它。通常的模式是这样的:

// Parent thread:
thread_arg *arg = malloc(sizeof(*arg));
...
pthread_create(..., &thread_proc, arg);

void *thread_proc(void *t_arg)
{
    thread_arg *arg = t_arg;

    // Thread code goes here
    ...
    free(arg);
    return exit_status;
}
于 2013-04-21T02:46:09.637 回答