-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRead.cpp
More file actions
92 lines (74 loc) · 2.39 KB
/
Read.cpp
File metadata and controls
92 lines (74 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <fstream>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <mutex>
#include <string>
using namespace std;
// Define a structure for PCB
struct PCB {
int processID; // Unique process identifier
string fileName; // File to be read by the process
int* sharedMemory; // Reference to shared memory for resource management
};
int *SharedData;
mutex mtx;
void* readFile(void* arg) {
PCB* pcb = (PCB*)arg; // Cast the argument back to PCB type
string fname = pcb->fileName;
ifstream file(fname);
if (file.is_open()) {
string line;
cout << "Contents of file \"" << fname << "\":" << endl;
while (getline(file, line)) {
mtx.lock();
cout << line << endl;
mtx.unlock();
}
file.close();
} else {
cout << "Failed to open file \"" << fname << "\" for reading or the file does not exist!" << endl;
}
pthread_exit(NULL);
}
int main() {
int shmid = shmget((key_t)8749, sizeof(int), IPC_CREAT | 0666);
if (shmid == -1) {
perror("Failed!");
return 1;
}
SharedData = (int*)shmat(shmid, NULL, 0);
if (SharedData == (int*)(-1)) {
perror("Failed!");
return 1;
}
cout << "\n\tProcess Requirements:\n";
cout << "Memory: 400MB\n";
cout << "Hard Disk Space: 100MB\n";
cout << "Number of Cores: 1" << endl;
cout << "Available Memory: " << *SharedData << endl;
if (*SharedData < 400) {
cout << "\tInsufficient resources to create a new process." << endl;
do {
// Keep waiting until sufficient resources are available
} while (*SharedData < 400);
}
cout << "Memory Allocation Done to This Process!" << endl;
// Update available memory after memory allocation
*SharedData -= 400;
string fileName;
cout << "Enter name of the file to read: ";
getline(cin, fileName);
// Create a PCB for the current process
PCB currentProcess;
currentProcess.processID = 1; // Assuming a unique process ID
currentProcess.fileName = fileName;
currentProcess.sharedMemory = SharedData; // Reference to shared memory
pthread_t readThread;
pthread_create(&readThread, NULL, readFile, (void*)¤tProcess);
pthread_join(readThread, NULL);
// Update available memory after reading the file
*SharedData += 400;
return 0;
}