// C program to implement Peterson’s Algorithm for given program
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdbool.h>
#include <stdio.h>
#define BSIZE 27 // Buffer size
#define PWT 2 // Process1 wait time limit
#define CWT 1 // Process2 wait time limit
int shmid1, shmid2, shmid3, shmid4;
key_t k1 = 5491, k2 = 5812, k3 = 4327, k4 = 3213;
bool* SHM1;
int* SHM2;
int* SHM3;
FILE *ptr1;
FILE *ptr2;
int main()
{
char file1[40],file2[40], chr;
printf("Enter the file name to be read: ");
scanf("%s",file1);
printf("Enter the file name to be written to: ");
scanf("%s",file2);
shmid1 = shmget(k1, sizeof(bool) * 2, IPC_CREAT | 0660); // flag
shmid2 = shmget(k2, sizeof(int) * 1, IPC_CREAT | 0660); // turn
shmid3 = shmget(k3, sizeof(char) * BSIZE, IPC_CREAT | 0660); // buffer
if (shmid1 < 0 || shmid2 < 0 || shmid3 < 0 || shmid4 < 0) {
perror("Main shmget error: ");
exit(1);
}
SHM3 = (char*)shmat(shmid3, NULL, 0);
int i = 0; // Process2
int j = 1; // Process1
int pid1,pid2;
if (pid1=fork() == 0) // Process1 code
{ ptr1=fopen(file1,"r");
SHM1 = (bool*)shmat(shmid1, NULL, 0);
SHM2 = (int*)shmat(shmid2, NULL, 0);
SHM3 = (char*)shmat(shmid3, NULL, 0);
if (SHM1 == (bool*)-1 || SHM2 == (int*)-1 || SHM3 == (char*)-1) {
perror("Process1 shmat error: ");
exit(1);
}
bool* flag = SHM1;
int* turn = SHM2;
char* buf = SHM3;
while (chr!=EOF) {
flag[j] = true;
printf("Process1 is ready now.\n\n");
*turn = i;
while (flag[i] && *turn == i)
;
// Critical Section Begin
chr=getc(ptr1);
while(chr!='\n'&& chr !=EOF){
*buf=chr;
chr=getc(ptr1);
buf++;
}
*buf=chr;
buf++;
// Critical Section End
flag[j] = false;
int wait_time = PWT;
printf("Process1 will wait for %d seconds\n\n", wait_time);
wait(PWT);
}
exit(0);
}
if (pid2=fork() == 0) // Process2 code
{ wait();
ptr2=fopen(file2,"w");
SHM1 = (bool*)shmat(shmid1, NULL, 0);
SHM2 = (int*)shmat(shmid2, NULL, 0);
SHM3 = (char*)shmat(shmid3, NULL, 0);
if (SHM1 == (bool*)-1 || SHM2 == (int*)-1 || SHM3 == (char*)-1) {
perror("Process2 shmat error:");
exit(1);
}
bool* flag = SHM1;
int* turn = SHM2;
char* buf1 = SHM3;
flag[i] = false;
while(*buf1!=EOF){
printf("%d",buf1);
flag[i] = true;
printf("Process2 is ready now.\n\n");
*turn = j;
while (flag[j] && *turn == j)
;
// Critical Section Begin
while(*buf1!="\n" && *buf1!=EOF ){
fputc(*buf1,ptr2);
buf1++;
}
if(*buf1!="\n")
fputc("\n",ptr2);
// Critical Section End
flag[i] = false;
int wait_time = CWT;
printf("Process2 will sleep for %d seconds\n\n", wait_time);
wait(CWT);
}
exit(0);
}
// Waiting for both processes to exit
wait(pid1);
wait(pid2);
printf("Transfer completed\n");
return 0;
}