What happens if sem_init () is called twice?

The sem_init () man page says: "Initializing a semaphore that has already been initialized leads to undefined behavior." Why is this and what exactly will happen on Linux?

This does not make sense to me, because when you call sem_init () for the first time, (uninitialized) sem_t may have the exact content as initialized sem_t - if the manual is correct, then sem_init () just doesn't work.

+4
source share
2 answers

On Linux, where semaphores are implemented without any system resources, it sem_initsimply populates the elements of the structure sem_t, and therefore nothing bad will happen if it calls more than once. However, on the whole, much worse can happen.

If it sem_tis just a dummy object containing a pointer to the selected object (note: this cannot work for process semaphores), you will leak memory by calling sem_initseveral times.

Similarly, if you sem_tsimply contained a link (for example, the file descriptor number) to a kernel-managed resource, you could leak these kernel resources by calling sem_initmore than once.

, , / sem_t ( - ), , sem_init sem_t, .

POSIX , (, , , ) undefined, , .

+3

API. , , .

, C ( ). , , , . .

API , . . , sem_init , , , . () , , .

API :

  • API?
  • ? ( /).
  • API?
  • ?
  • API ?
  • / ?
  • ...

, , . . , - , , , , .

? , undefined , , . , . , .

() sem_t sem_t

. , , sem_t , sem_init malloc. - sem_t , , , .

+2

All Articles