在使用pthread_create创建的线程之间读取和写入管道时,是否需要关闭 fds

Do I need to close fds when reading and writing to the pipe among threads created using pthread_create?

本文关键字:管道 是否 fds pthread create 创建 读取 之间 线程      更新时间:2023-10-16

我正在开发一个客户端服务器应用程序。下面是来自客户端的代码。

pipe_inputpipe_output是共享变量。

        int fds[2];
            if (pipe(fds)) {
                        printf("pipe creation failed");
                    }  else {
                        pipe_input = fds[0];
                        pipe_output = fds[1];
                        reader_thread_created = true;
                        r = pthread_create(&reader_thread_id,0,reader_thread,this);
                        }

 void* reader_thread(void *input)
    {
    unsigned char id;
        int n;
        while (1) {
            n = read(pipe_input , &id, 1);
            if (1 == n) {
                //process
            }if ((n < 0) ) {
                printf("ERROR: read from pipe failed");
                break;
            }
        }
        printf("reader thread stop");
        return 0;
    }

还有一个编写器线程,它从服务器写入事件更改的数据。

void notify_client_on_event_change(char id)
{
    int n;
    n= write(pipe_output, &id, 1);
    printf("message written to pipe done ");
}

我的问题是我是否需要关闭读取器线程中的写入端并在写入器线程的情况下关闭读取结束。在析构函数中,我正在等待读取器线程退出,但有时它不会从读取器线程退出。

[

...]我是否需要关闭读取器线程中的写入端,并在写入器线程的情况下关闭读取端[?

由于这些 fds ">是共享的",因此在一个线程中关闭它们将关闭所有线程的它们。我怀疑这不是你想要的。