help with shared memory

what i want to do is have an int that can been written into by 2 processes but my code doesn't seem to work.

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include<stdio.h>
#define KEY1 (1492)
int main()
{

	int shmid;
	volatile int * addr;
	pid_t  pid1;
	
	shmid=shmget(KEY1,4*1,SHM_R|SHM_W);
	addr=shmat(shmid,0,4);
	addr=0;
	pid1=fork();
	if(pid1==0)
	{
		addr[0]=1;
		sleep(1);
		addr=2;
		sleep(1);
		addr=3;
	}
	else
	{	
		printf("addr is %i \n",addr);
		sleep(1);
		printf("addr is %i \n",addr);
		sleep(1);
		printf("addr is %i \n",addr);
		sleep(1);

		
		if((shmctl(shmid,IPC_RMID, 0)) < 0) 
		{
			printf("shmctl shared mem delete NG\n");
			exit(1);
		} 				
		printf("shmctl shared mem delete OK\n"); 
	}

	return 0;
}

Check the return value shmid, then check which errno is set. I think you will see ENOENT as the error - the IPC_CREAT flag is not set.

You can also run into trouble by picking a number like that.

you have checked only for the if pid == 0 and the else part

you need to check for condition when fork fails and returns a -1.

fork();
equals = -1
equals = 0
equals = positive value

i only check pid1 equal zero because i want to tell the difference between the parent and the child.

and i don't understand the IPC_CREAT flag. i know how to use them with semaphores but not shared memory.

i used this link's instr but i still cant get it to work.

http://www.ecst.csuchico.edu/~beej/guide/ipc/shmem.html

try

shmid=shmget(KEY1, 4*1, SHM_R | SHM_W| IPC_CREAT);

This will create the segment if it does not exists

even better:

shmid=shmget(IPC_PRIVATE, 4*1, SHM_R | SHM_W| IPC_CREAT);

This handles the problem for existing a pre-existing key that belongs to another process. Those keys are assigned sequentially by the kernel. You can't know ahead of time if "1492" is in use already or not.

Plus, based on the OP's repsonses, I would suggest to the OP to read the man page for shmget. Simply copying code off the internet is NOT a good idea. That code has several problems, as pointed out.

ALWAYS check return codes.