I'm studying shared memory and now I'm writing a program that use system v shared memory. This is my code:
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <sys/shm.h> #include <sys/ipc.h> #include <fcntl.h> #define PG_SIZE sysconf(_SC_PAGESIZE) #define PROJ_ID 1 #define SHM_FILE "/dev/shm/myshm" void executeChild( void ); void executeParent( void ); int main ( int argc, char *argv[] ) { unlink(SHM_FILE); int fd = creat(SHM_FILE, S_IRWXU ); if( fd == -1 ){ perror("Segment memory file creation failed"); exit(1); } int pid = fork(); if( pid < 0){ perror("Fork failed\n"); return EXIT_FAILURE; } if( pid ){ executeParent(); printf("Parent waiting...\n"); int status = 0; wait(&status); //wait for child process printf("Parent done\n"); }else{ executeChild(); } close( fd ); return EXIT_SUCCESS; } void executeChild( void ) { printf("Child running\n"); sleep(15); } void executeParent( void ) { printf("Parent running\n"); key_t token = ftok(SHM_FILE, PROJ_ID); if( token == -1 ){ perror("Token creation failed"); exit(1); } int segment = shmget( token, PG_SIZE, IPC_CREAT | IPC_EXCL | S_IRWXU); if ( segment == -1 ){ perror("Segment creation failed"); exit(1); } void * shm_ptr = shmat(segment, NULL, 0); if( shm_ptr == (void *)(-1) ){ perror("Segment attachament failed"); exit(1); } printf("Shared memory ( %d ) attached\n", segment); struct shmid_ds shm_info; if( shmctl(segment, IPC_STAT, &shm_info) == -1 ){ perror("shmctl failed"); exit(1); } printf("Segment size = %zu\n", shm_info.shm_segsz); printf("Writing...\n"); const char * test = "teste"; memcpy(shm_ptr, test, strlen(teste)); } The file of the shared memory is created. I can see it on /dev/shm and icps commando also show it. But the size of the file of my shared memory segment is not increasing. So I presume that the memcpy is not working properly like I was expected. Why?