Write a C Program to Implement Inter Process Communication

Aim:

To write a C Program to Implement Inter-Process Communication.

Description:

  • In the discussion of the fork() system call, we mentioned that a parent and their children have separate address spaces.
  • While this would provide a more secure way of executing parent and children processes (because they will not interfere with each other), they shared nothing and have no way to communicate with each other.
  • Shared memory is an extra piece of memory that is attached to some address spaces for their owners to use. As a result, all of these processes share the same memory segment and have access to it.
  • Consequently, race conditions may occur if memory accesses are not handled properly. The following figure shows two processes and their address spaces.
  • The yellow rectangle is a shared memory attached to both address spaces and both process 1 and process 2 can have access to this shared memory as if the shared memory is part of its own address space.
  • In some sense, the original address spaces is “extended” by attaching this shared memory.
  • Shared memory is a feature supported by UNIX System V, including Linux, SunOS, and Solaris.
  • One process must explicitly ask for an area, using a key, to be shared by other processes. This process will be called the server.
  • All other processes, the clients, that know the shared area can access it. However, there is no protection to shared memory, and any process that knows it can access it freely.
  • To protect a shared memory from being accessed at the same time by several processes, a synchronization protocol must be set up.
  • A shared memory segment is identified by a unique integer, the shared memory ID.
  • The shared memory itself is described by a structure of type shmid_ds in the header file sys/shm.h. To use this file files sys/types.h and sys/ipc.h must be included.

Algorithm:

  1. Create the pipe and create the process.
  2. Get the input in the main process and pass the output to the child process using pipe.
  3. Perform the operation given in the child process and print the output.
  4. Stop the program.

Program:

#include<stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

int main()
{
if(fork()==0)
{
key_t key = ftok("shmfile",65);
int shmid = shmget(key,1024,0666|IPC_CREAT);
char str = (char) shmat(shmid,(void*)0,0);
printf("Write Data : \n");
scanf("%s",str);
printf("Child process written in memory: %s\n",str);
shmdt(str);
}
else
{
wait(0);
key_t key = ftok("shmfile",65);
int shmid = shmget(key,1024,0666|IPC_CREAT);
char str = (char) shmat(shmid,(void*)0,0);
printf("Parent reads from memory       : %s\n",str);
shmdt(str);
shmctl(shmid,IPC_RMID,NULL);
}
return 0;
}

Result:

Thus the implement inter process communication program was executed Successfully

Leave a Comment