Мне нужно организовать безымянный канал между двумя потоками, первый поток должен писать в канал, второй - читать из него. Делаю следующим образом:#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
static pthread_mutex_t mutex;
void* thread1_f(void* arg)
{
close(fds[0]);
int a = 2000;
pthread_mutex_lock(&mutex);
write(fds[1], &a, sizeof(int));
pthread_mutex_unlock(&mutex);
sleep(1);
close(fds[1]);
return NULL;
}
void* thread2_f(void* arg)
{
close(fds[1]);
int a;
pthread_mutex_lock(&mutex);
read(fds[0], &a, sizeof(int));
pthread_mutex_unlock(&mutex);
printf("%d\n", a);
close(fds[0]);
return NULL;
}
int main()
{
int fds[2];
pipe(fds);
pthread_mutex_init(&mutex, NULL);
pthread_t thread1_id;
pthread_t thread2_id;
pthread_create(&thread1_id, NULL, &thread1_f, &fds);
pthread_create(&thread2_id, NULL, &thread2_f, &fds);
pthread_join(thread1_id, NULL);
pthread_join(thread2_id, NULL);
pthread_mutex_destroy(&mutex);
return 0;
}
Но во втором потоке функция read возвращает ошибку EBADF.
Подскажите, пожалуйста, где и что я сделал неправильно?