Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared memory for fork

I want to create a shared memory between two process. I used fork(). A child tries to change this shared memory and mother creates another child so new child tries to change same memory so on. here is my code in C programing. (ubuntu)

mylist ch=NUL; 
f=fork();
if(!f){
        pba=shmget(KEYSHM,sizeof(char),0); /*created shared memory*/
        ch=(mylist *) shmat(pba,0,0);
        ch->name=ugur;
        ch->surname=cedric;
...do something...
}
else{
        if(ch)
        printf("this is top of mylist %s"ch->name);
.......do something
}

It never writes ch->name. why? I created a shared memory. Why parent process cannot read?

like image 316
Iguramu Avatar asked May 16 '26 12:05

Iguramu


2 Answers

For the memory to be shared, both the parent and the child must access the same shared memory.

You have two options, the simpler and the harder:

  • Create and attach to the shared memory before forking. Both parent and child automatically have access to the same shared memory.

  • Fork first, and then both parent and child must attach to the shared memory separately. Once the processes have forked, they no longer share memory, and in particular, anything allocated in the child is not accessible in the parent.

You need to allocate more than 1 character of shared memory to store useful strings such as names.

like image 120
Jonathan Leffler Avatar answered May 18 '26 02:05

Jonathan Leffler


You have a race condition, what if the parent runs before the child , and you try to access ch-> before the child has placed anything there ?

You also allocate only 1 byte(sizeof(char)) but you're trying to treat that as a pointer to a struct - you need to allocate enough space for mylist - unless you've done so erlier. You'd need the IPC_CREAT flag to shmget somewhere too.

like image 42
nos Avatar answered May 18 '26 01:05

nos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!