Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 访问共享内存段时的进程块_C_Shared Memory - Fatal编程技术网

C 访问共享内存段时的进程块

C 访问共享内存段时的进程块,c,shared-memory,C,Shared Memory,我正在开发一个程序,该程序在共享内存段中存储一个struct,这样我就可以同时使用主进程和多个线程中的数据。我还使用互斥信号量(pthread\u mutex\u lock()/pthread\u mutex\u unlock())来保证要访问共享内存段的进程之间的互斥 首先,一个线程锁定结构,并用信息填充它: void * client_thread(void *argc) { thread_input *t_input = (thread_input *) argc; //str

我正在开发一个程序,该程序在共享内存段中存储一个
struct
,这样我就可以同时使用主进程和多个
线程中的数据。我还使用互斥信号量(
pthread\u mutex\u lock()
/
pthread\u mutex\u unlock()
)来保证要访问共享内存段的进程之间的互斥

首先,一个
线程
锁定
结构
,并用信息填充它:

void * client_thread(void *argc) {

    thread_input *t_input = (thread_input *) argc;  //struct that stores data usefull for the thread such as the shm segment

    shm_data *shmdata;   //<-- shared struct
    shmdata = shmat(t_input->memid, 0, 0);

    //...

    pthread_mutex_lock(t_input->mtx);
        shmdata->station = malloc((strlen(data.station)+1) * sizeof(char));
        strcpy(shmdata->station, data.station);
        shmdata->temperature = data.temperature;
        shmdata->humidity = data.humidity;
        shmdata->pressure = data.pressure;
        shmdata->precipitation = data.precipitation;
    pthread_mutex_unlock(t_input->mtx);

    //...
}

我已经测试了
thread
main
进程中的内存id,它是相同的,我保证
thread
code将首先执行,然后执行
main
进程。为什么程序在那里被阻塞?

shmdata->station
在堆上分配,因此它在线程之间共享,而不是在进程之间共享。只有一个指针是共享的,但它在其他进程上下文中没有意义。尝试确定
shm\u data
struct@tstanisl在这种情况下,当我使用线程时,它不应该工作吗?您是否初始化了
mtx
?所有线程共享相同的地址空间。不管线程是在哪里以及如何产生的,把全部代码放在这里。只要编译并产生故障,您就可以跳过不相关的部分。
shmdata->station
是在堆上分配的,因此它在线程之间共享,而不是在进程之间共享。只有一个指针是共享的,但它在其他进程上下文中没有意义。尝试确定
shm\u data
struct@tstanisl在这种情况下,当我使用线程时,它不应该工作吗?您是否初始化了
mtx
?所有线程共享相同的地址空间。不管线程是在哪里以及如何产生的,把全部代码放在这里。只要编译并产生故障,就可以跳过不相关的部分。
//...

shm_data *shmdata;  //<-- shared struct
shmdata = shmat(memid, 0, 0);

pthread_mutex_lock(&mtx);
    write(1, "Station:\n", strlen("Station::")); //Prints fine
    write(1, shmdata->station, strlen(shmdata->station)); //<-- Program blocks here
    write(1, "Done!\n", strlen("Done!!")); //Program does not reach this point or any further
pthread_mutex_unlock(&mtx);

//...