Question

Could anyone tell me another way to share strings in C between processes using shared memory? I've only achieved this shoddy way using fors. I want to use something like strcpy or similars. With int is very simple, but when pointers start playing becames so dificult form me. Here is the way I've achived in order to look for other ways:

int memid,*nptr,i;
char mezua[50];
struct shmid_ds buff;


if ((memid=shmget(IPC_PRIVATE,sizeof(mezua),0600|IPC_CREAT))<0){
    perror("shmget error");
    exit(-1);
}
printf("%d\n",memid);

if((nptr=(char*)shmat(memid,0,0))==(char*)-1){
    perror("shmat error");
    exit(-1);
}

printf("Sartu nahi duzun mezua:\n");
__fpurge(stdin);
scanf("%s",mezua);


for(i=0;i<strlen(mezua);i++){
    *(nptr+i)=mezua[i];
}  
//**HERE WOULD GO THE OTHER WAY TO COPY STRINGS INTO SHARED MEMORY**


for(i=0;*(nptr+i)!='\0';i++)
    printf("%c",*(nptr+i)); 
//**HERE WOULD GO THE OTHER WAY TO READ STRINGS FROM SHARED MEMORY**


if(shmdt(nptr)<0){
    perror("shmdt error");
    exit(-1);
    }

    if(shmctl(memid,IPC_RMID,&buff)==-1){
        perror("shmctl error");
        exit(-1);
    }

Thanks a lot!

Have a nice code!!

Was it helpful?

Solution

You might like to read man strcpy.

Make nptr a char* and do

strcpy(nptr, mezua); /* Copies from mezuato SHM. */

....

strcpy(mezua, nptr); /* Copies form SHM to mezua. */
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top