【问题标题】:the gloabl file descriptor not shared between threads on linux全局文件描述符不在Linux上的线程之间共享
【发布时间】:2018-12-04 01:47:57
【问题描述】:

我正在linux上开发一个小型c程序,两个线程需要使用相同的文件描述符(实际上是unix域套接字),所以我只是设置了一个文件描述符的全局变量,在一个线程打开文件并使用另一个线程,但似乎没有共享,我将代码简化如下:

#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<fcntl.h>

int gfd  = 0;
int test = 2;
void* thr_fun1(void* arg)
{
    printf("thr 1 gfd %d test %d \n",gfd, test);
}

int main()
{
    int gfd = open("aaa.txt", O_RDWR | O_CREAT, 0664);
    pthread_t tid;
    int err;
    printf("thr main gfd %d test %d \n",gfd, test);
    test = 12;
    err = pthread_create(&tid, NULL, thr_fun1, NULL);
    if(0 != err)
    printf("can't create thread\n");
    sleep(2);
}

操作系统是 Ubuntu 16.04.4 LTS(GNU/Linux 4.13.0-36-generic x86_64)

liu@ns:~$ gcc -pthread -o fd fd.c
liu@ns:~$ ./fd
thr main gfd 3 test 2
thr 1 gfd 0 test 12

我的问题是:为什么全局变量test是共享的,而gfd却不是?

【问题讨论】:

  • 因为范围。你在main 中声明了一个不同的gfd

标签: c linux multithreading


【解决方案1】:

简短的回答是,您在线程中打印的名为gfd 的变量是全局变量,但您在main 中设置的变量不是。您声明了两个不同的变量:

  1. int gfd = 0; 这个其实是全球性的。
  2. int gfd = open("aaa.txt", O_RDWR | O_CREAT, 0664); 这个是 main 本地的。

main 中的打印输出指的是#2,而thr_fun1 中的打印输出指的是#1。

要改变这一点,请将 main 中的赋值修改为赋值,而不是声明,方法是删除类型:

gfd = open("aaa.txt", O_RDWR | O_CREAT, 0664);

【讨论】:

    猜你喜欢
    • 2012-12-03
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 2010-11-23
    • 2014-01-19
    相关资源
    最近更新 更多