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);
//...