c - shmat returns segmentation fault(core dumped) -


im trying write shared memory reason after call shmat() , strcpy segmentation fault(core dumped) why that?

this code:

int fd,shmid; key_t shmkey; char *shm_add; pid_t pid,pid1=0,pid2=0;  shmkey=ftok("shmdemo.c",'j'); if ( shmkey == (key_t)-1 )  {     printf("main: ftok() shm failed\n");     return -1; } shmid=shmget(shmkey, 50, 0666 | ipc_creat | ipc_excl); if (shmid == -1) {     printf("main: shmget() failed\n");     return -1; } shm_add=(char *)shmat(shmid,0,0); if ( shm_add==null ) {     printf("main: shmat() failed\n");     return -1;  }  strcpy(shm_add,"hello"); 

edit: have file name shmdemo.c on directory, , errno of shmget "file exists" when delete "shmdemo.c" directory, new errno comes in ftok "no such file or directory".

thank you, asaf.

answerifying various comments. when call:

shmget(..., ipc_creat | ipc_excl); 

what you're saying flags is: create new shared memory segment key, and make sure no shared memory segment exists key already.

if use:

shmget(..., ipc_creat); 

you're saying: if shared memory segment already exists key, return it; otherwise create new 1 key , return that.

generally, don't want second variant of call. concurrency hard enough without adding nondeterminism of own. (i.e. letting whichever of bunch of cooperating processes comes first create shared memory; opposed having designated "owner" process.)

when using first call, if shared memory segment exists @ given key, syscall fails errno value eexists. sysv ipc persistent, don't automatically cleaned after program exits like, say, file descriptors. (in fact, they're more analogous temporary files.)

you should clean them in program using shmctl(shmid, ipc_rmid, null);. can check stray ipc objects using ipcs , remove ones left behind ipcrm or cleanipcs.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -