gpt4 book ai didi

c - 管道无法通过 pthread_t 工作

转载 作者:行者123 更新时间:2023-11-30 15:08:45 25 4
gpt4 key购买 nike

我现在尝试通过两个线程(主线程和第二个线程)之间的管道发送一些数据,但我收到有关文件描述符的 errno 9。我认为当涉及线程时文件描述符是重复的,但这里似乎不是这种情况。它通常会返回“read from bf hi”,但它不会。你能帮我解决这个问题吗?谢谢。这是代码

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>

pthread_mutex_t mutex;
int tube[2];

void * fonction(){
if(close(tube[0])==-1){
perror("close error \n");
exit(EXIT_FAILURE);
}
printf("son \n");
if(write(tube[1],"hi",2)<0){
perror("write error \n");
exit(EXIT_FAILURE);
}
printf("errno %d \n",errno);
pthread_exit(NULL);
}

int main(){
pthread_t a;
if(pipe(tube)==-1){
perror("pipe error \n");
exit(EXIT_FAILURE);
}
char buffer[2];
pthread_mutex_init(&mutex,NULL);
close(tube[1]);
pthread_create(&a,NULL,fonction,&tube[1]);
pthread_join(a,NULL);
read(tube[0],buffer,2);
printf("read from bf %s \n",buffer);
return EXIT_SUCCESS;
}

Ps:正如 timrau 在这里建议的那样( Pthread_t not starting )我使用 pthread_join 但我想这不是正确的方法

最佳答案

I thought file descriptor were duplicated when thread are involved but it seems it's not the case here.

不,这不是真的。

进程内的所有线程共享这些文件描述符(以及其他资源)。由于您关闭了管道的写入端,因此您的 write() (在线程中完成)失败。

同一进程的线程可以直接相互通信,因为它们共享地址空间。例如,您可以使用全局变量在线程之间进行通信(通过适当的同步),或者您可以 malloc() 一些内存并将其传递给线程以发送数据。

您似乎期望的那种“共享”是在由共同祖先通过fork()创建的进程之间使用的。当 fork 时,文件描述符(以及其他)会被复制,您可以在每个进程的一端并通过管道的另一端进行通信。请参阅此处的简单示例:Creating Pipes in C.

关于c - 管道无法通过 pthread_t 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37170117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com