c - 管道无法通过 pthread_t 工作

标签 c pthreads pipe

我现在尝试通过两个线程(主线程和第二个线程)之间的管道发送一些数据,但我收到有关文件描述符的 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/

相关文章:

c++ - 使用 boost::asio 时如何防止 SIGPIPE?

使用三个 execlp 创建两个管道 C 系统编程某处出现小错误

c - 添加两个大数字作为字符串

带重定向的 stdin 上的 C 系统行为

c - 传递给 pthread 后结构发生变化

c - Linux 中的线程同步?

c - C 数据流库

Cygwin html 到浏览器

c++ - 在 C/C++ DOS 中为文本着色的最简单方法?

c++ - 在 64 位 Ubuntu 中使用 pthread 从 void* 转换为 int