进程与线程学习指南
1. 共享内存与线程基础
在Linux系统中,内存通常取自挂载在 /dev/shm
或 /run/shm
的 tmpfs
文件系统。以下是一段使用共享内存的代码示例:
/* Map the shared memory */
shm_p = mmap(NULL, SHM_SEGMENT_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED, shm_fd, 0);
if (shm_p == NULL) {
perror("mmap");
exit(1);
}
return shm_p;
int main(int argc, char *argv[])
{
char *shm_p;
printf("%s PID=%d\n", argv[0], getpid());
shm_p = get_shared_memory();
while (1) {
printf("Press enter to see the current contents of shm\n");
getchar();
sem_wait(demo_sem);
printf("%s\n", shm_p);
/* Write our signature to the shared memory */
sprintf(shm_p, "Hello from process %d\n", getpi