简体   繁体   English

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

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

There is a client server application I am working on. 我正在处理一个客户端服务器应用程序。 Below is the code from client side. 下面是来自客户端的代码。

pipe_input , pipe_output are shared variables. 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;
    }

There is a writer thread also which writes data on event change from server. 还有一个写程序线程,该线程用于在服务器发生事件更改时写入数据。

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

My question is do I need to close the write end in reader thread and read end in case of writer thread. 我的问题是我需要关闭读取器线程中的写端,而在写入器线程中需要关闭读端。 In the destructor, I am waiting for reader thread to exit but sometimes it doesn't exit from reader thread. 在析构函数中,我正在等待读取器线程退出,但有时它不会从读取器线程退出。

[...] do i need to close the write end in reader thread and read end in case of writer thread[?] [...]我是否需要关闭读取器线程中的写入端并在写入器线程中关闭读取端[?]

As those fds " are shared ", closing them in one thread would close them for all threads. 当这些fds被“ 共享 ”时,在一个线程中关闭它们将为所有线程关闭它们。 That is not what you want, I suspect. 我怀疑那不是您想要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM