使用pthread_create创建的线程之间读写管道时是否需要关闭fds?
Do I need to close fds when reading and writing to the pipe among threads created using pthread_create?
我正在开发一个客户端服务器应用程序。以下是来自客户端的代码。
pipe_input
、pipe_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 ");
}
我的问题是我是否需要在 reader 线程中关闭写端并在写线程的情况下关闭读端。在析构函数中,我正在等待 reader 线程退出,但有时它不会从 reader 线程退出。
[...] do i need to close the write end in reader thread and read end in case of writer thread[?]
因为那些 fds“ 是共享的”,在一个线程中关闭它们将会为所有线程关闭它们。我怀疑那不是你想要的。
我正在开发一个客户端服务器应用程序。以下是来自客户端的代码。
pipe_input
、pipe_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 ");
}
我的问题是我是否需要在 reader 线程中关闭写端并在写线程的情况下关闭读端。在析构函数中,我正在等待 reader 线程退出,但有时它不会从 reader 线程退出。
[...] do i need to close the write end in reader thread and read end in case of writer thread[?]
因为那些 fds“ 是共享的”,在一个线程中关闭它们将会为所有线程关闭它们。我怀疑那不是你想要的。