Вопрос

I have problem with locking shared memory. This the code:

if(shmctl(id,SHM_LOCK,&sgmlock)==FAILED)
exit_failed("shmctl failed");
printf("%d got the lock\n", getpid()) ;

if(arr[CHLD3_ID_SET]==1){
  arr[CHLD3_ID_SET]++;
  puts("2a");
}
else if(arr[CHLD3_ID_SET]==2)
{
  puts("2b");

  arr[CHLD3_ID]=EMPTY;
  arr[CHLD3_ID_SET]=EMPTY;
}

printf("%d got  unlocked\n", getpid()) ;

if(shmctl(id,SHM_UNLOCK,&sgmlock)==FAILED)
exit_failed("shmctl failed");

So the first how get in increase the arr[CHLD3_ID_SET] and the second reset the cell in the array.

the 2 process are fork of the father(and use the same shared memory) if the program is not stack in this section there is no problem

this is the output for the code:

10938 got the lock
10939 got the lock
2a
10938 got unlocked
3
2b
10939 got unlocked
3

(3 is print out of the lock section.)

so we can see that one lock,and the secend can get into the lock section. what i doing wrong?

thank you!!

Это было полезно?

Решение

SHM_LOCK is not a mutual-exclusion tool. It is just a request to the kernel that the pages in the shared memory segment not be swapped out of memory - similar to mlock().

If you want mutual exclusion using the SYSV IPC APIs (shmctl() is one of these), then you need to use SYSV semaphores (semctl() / semget() / semop()).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top