Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

469
Visualizações
Why does sem_open work with fork() without shared memory?

This program works (I tested it), even though the semaphore is not in shared memory. Note how I create the variable once - before the fork().

On the other hand, a semaphore created with sem_init() needs to be in shared memory to work. But it's still a sem_t structure, so why doesn't it require shared memory?

Are the contents of the sem_t structure somehow different?

sem_t *s = sem_open("mysemaphore1", O_CREAT, 0600, 0);
if (fork()) {
    sleep(3);
    sem_post(s);
} else {
    sem_wait(s);
    printf("Woke\n");
}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The semaphore created by sem_open() is a named semaphore. The basic purpose of named semaphore is to be used between unrelated processes. The semaphore created by sem_init() is an unnamed semaphore. It is light weight than the named semaphore and needs to be put in shared memory if used between related processes. If used between threads of the same process, it can be kept in global variable.

The pointer returned by the sem_open() is actually a pointer to a memory mapped by mmap() with MAP_SHARED flag set. Since such kind of memory persists across fork(), hence you are able to use the same variable in both parent and child to access the named semaphore.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda