Jump to content

I'm getting asegmentation fault when I try to write a 1GB array to shared memory. When I reduce the size it runs fine.

 

//gcc -o producer shm-posix-producer.c -lrt

/**
 * Simple program demonstrating shared memory in POSIX systems.
 *
 * This is the producer process that writes to the shared memory region.
 *
 * Figure 3.17
 *
 * @author Silberschatz, Galvin, and Gagne
 * Operating System Concepts  - Ninth Edition
 * Copyright John Wiley & Sons - 2013
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>
int main()
{
	const int SIZE = 1024*1024*1024;
	const char *name = "shared_memory";

	int shm_fd;
	char *ptr, *start;

	/* Cria um segmento de memória compartilhado 
	e retorna um descritor de arquivo. Este
	arquivo não existe fisicamente em disco,
	ele é apenas um arquivo virtual criado em
	em um sistema de arquivos temporário (tmpfs)
	dentro de /dev/shm/xxx. */
	shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);

	/*shm_open: cria ou abre um objeto de
	memória compartilhado.

	/* O tamanho inicial de um segmento é de 0 bytes.
	A função "ftruncate" define o tamanho do
	segmento.*/
	ftruncate(shm_fd,SIZE);

	/* Mapeia o segmento de memória para o espaço
	 de endereçamento do processo. Dessa forma, o
	segmento poderá ser acessado por meio de um
	ponteiro. 

	/* O primeiro parâmetro "0" indica que o kernel
	escolhe o endereço no qual o mapeamento será 
	criado. Valores diferentes de "0" são utilizados
	como sugestões para o Kernel.
	O último parâmetro "0" indica o ponto de início
	do mapeamento no arquivo.
	No caso abaixo, o mapeamento contém SIZE bytes
	iniciando em 0.*/
	ptr = mmap(0,SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
	if (ptr == MAP_FAILED) {
		printf("Map failed\n");
		return -1;
	}
	/*Depois que o segmento de memória foi
	mapeado para o espaço de endereçamento
	do processo, o arquivo ("shm_fd") pode
	ser fechado.*/

	/*Escreve na memória compartilhada.*/
	start = ptr;
	sprintf(ptr,"Hello: ");
	ptr += 7; //Move o ponteiro
	int c;
	for (c = 0; c <= SIZE; c++,ptr++)
        	*ptr = 97 + rand() % (123-97);
	*ptr = '\0';
	ptr++;
	*ptr=10;
	
	//memcpy(ptr,"conteudo",tamanho);
	return 0;
}

 

 

 

Link to comment
https://linustechtips.com/topic/1049344-write-array-to-shared-memory/
Share on other sites

Link to post
Share on other sites

18 minutes ago, IgorM said:

I'm getting asegmentation fault when I try to write a 1GB array to shared memory. When I reduce the size it runs fine.

Have you actually checked the size of your shm and how much free space there is?

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to post
Share on other sites

35 minutes ago, IgorM said:

I'm getting asegmentation fault when I try to write a 1GB array to shared memory. When I reduce the size it runs fine.


	ptr += 7; //Move o ponteiro
	int c;
	for (c = 0; c <= SIZE; c++,ptr++)
        	*ptr = 97 + rand() % (123-97);

 

If you reduce size by 7, does it still work?

Link to post
Share on other sites

39 minutes ago, IgorM said:

I'm getting asegmentation fault when I try to write a 1GB array to shared memory. When I reduce the size it runs fine.


	const int SIZE = 1024*1024*1024;

	--SNIP--

	for (c = 0; c <= SIZE; c++,ptr++)
        	*ptr = 97 + rand() % (123-97);
	*ptr = '\0';
	ptr++;
	*ptr=10;

 

You also got a bug there, you're writing past the allocated space. The for-loop should be for (c = 0; c < SIZE; c++,ptr++) or else c will reach size+1

Hand, n. A singular instrument worn at the end of the human arm and commonly thrust into somebody’s pocket.

Link to post
Share on other sites

2 minutes ago, Mira Yurizaki said:

Glad you figured it out :)

Thanks!

Now I have to figure out how to read only a segment of the shared memory I've created. THis following program only reads the entire shared memory

 

/**
 * Simple program demonstrating shared memory in POSIX systems.
 *
 * This is the consumer process
 *
 * Figure 3.18
 *
 * @author Gagne, Galvin, Silberschatz
 * Operating System Concepts - Ninth Edition
 * Copyright John Wiley & Sons - 2013
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <unistd.h>

int main()
{
	const char *name = "shared_memory";
	const int SIZE = 1024;

	int shm_fd;
	void *ptr;
	int i;

	/* open the shared memory segment */
	shm_fd = shm_open(name, O_RDONLY, 0666);
	if (shm_fd == -1) {
		printf("shared memory failed\n");
		exit(-1);
	}

	/* now map the shared memory segment in the 
	address space of the process */
	ptr = mmap(0,SIZE, PROT_READ, MAP_SHARED, shm_fd, 0);
	if (ptr == MAP_FAILED) {
		printf("Map failed\n");
		exit(-1);
	}

	/* now read from the shared memory region */
	printf("%s\n",(char*)ptr);
	printf("%d\n", *((int*)(ptr+strlen(ptr)+1))  );
	
	sleep(60);
	/* remove the shared memory segment */
//	if (shm_unlink(name) == -1) {
//		printf("Error removing %s\n",name);
//		exit(-1);
//	}

	return 0;
}

 

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×