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

281
Visualizações
shm_open and ftruncate() in Shared Memory Programming

I want to create a Shared Memory Object and truncate it to a specific size.

SHMSIZE is defined with 512

MODE is set with S_IRUSR | S_IWUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH

Here is my Code

char *shm_name = "SharedMemory";    
int fd; 

/* Open an Shared Memory Object for Read-/Write-Access */    
if((fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE) < 0)) {     
     perror("\nshm_open() in Caretaker failed");    
     exit(EXIT_FAILURE);
}

/* Truncate Shared Memory Object to specific size */
if((ftruncate(fd, SHMSIZE) < 0)) {
    perror("\nftruncate() in Caretaker failed");
    exit(EXIT_FAILURE);
}

While Debugging i watched that the return value of shm_open() is 0 every time, but i can see this object in /dev/shm. And while executing ftruncate() it returns every time with error "invalid argument".

Why fd is 0 every time and why ftruncate doesn't work? What should i do?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The order of operations in this statement is wonky:

if((fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE) < 0)) {

You're assigning the result of shm_open(...) < 0 to fd, which is definitely not what you want.

Move the comparison outside the parentheses:

if((fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE)) < 0) {
                                                   ^^^
over 4 years ago · Santiago Trujillo Relatório

0

You can also try by first declaring fd then comparing it to 0.

    int fd = shm_open(shm_name, O_RDWR | O_CREAT, MODE);
    if (fd < 0){
       perror("\nshm_open() in Caretaker failed");
    }

It brings about less confusion after all.

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