Shared Memory - String - Systems Lab - C Program


Program:

#include<stdio.h>
#include<unistd.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/wait.h>
#include<sys/types.h>
#include"string.h"
#define shmsize 100
#define shmmode (SHM_R|SHM_W|IPC_CREAT|IPC_EXCL)
#define shmkey (key_t)31
int size;
int main()
{
    int shmid1, shmid2, pid, status;
   
    int *shmdata1, *shmdata2, *shmdata;
   
    char str1[20],str2[20],str3[20];
    int i,j,k,size2,size3;
    struct shmid_ds *shmidds;
    shmid1 = shmget(shmkey,shmsize,shmmode);
    shmdata1 = (int*)shmat(shmid1,0,0);
    shmdata = shmdata1;
    printf("Enter the string:");
    scanf("%s",str1);
    size=strlen(str1);
    for(j=0;j<size;j++)
    {
        *shmdata1=str1[j];
        shmdata1=shmdata1+sizeof(char);
    }
    pid = fork();           
    if(pid == 0)
    {
        printf("Enter the string:");
        scanf("%s",str2);
        size2=strlen(str2);
        for(i=0;i<size2;i++)
        {
            *shmdata1=str2[i];
            shmdata1+=sizeof(char);
        }
        size=size+size2;
    }
    while((pid = wait(&status))!= -1);
    shmdata1=shmdata;
    for(i=0;i<size;i++)
    {
        str3[i]=*shmdata1;
        shmdata1+=sizeof(char);
    }
    str3[size]='\0';
    printf("%s\n\n\n\n\n\n",str3);
shmdt((void*)shmdata);
shmdt((void*)shmdata1);
shmctl(shmid1,IPC_RMID,shmidds);
    return 1;
}

Output:
nn@ubuntu:~$ gcc shmstr.c
nn@ubuntu:~$ ./a.out
Enter the string:hai
Enter the string:helo
haihelo





hai





nn@ubuntu:~$

1 comment:

Related Posts Plugin for WordPress, Blogger...