Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <semaphore.h>
- #include <stdlib.h>
- #include <stdio.h>
- #include <fcntl.h>
- #include <cstdlib>
- #include <iostream>
- #include <sys/types.h>
- #include <errno.h>
- #include <string.h>
- #include <unistd.h>
- #include <string>
- #include <fstream>
- using namespace std;
- int main(int argc, char* argv[])
- {
- fstream bufferFile;
- ifstream readFile;
- int sem1 = 1;
- int sem2 = 0;
- int aNum = 0;
- int childcount = 0;
- pid_t fork_return;
- bufferFile.open("buffer.txt.", ios::out);
- cout << "Writing to buffer file.\n";
- bufferFile << aNum;
- bufferFile.close();
- sem_t mutex;
- sem_init(&mutex,1,1);
- fork_return = fork( );
- while(childcount < 5){
- if (fork_return == 0) { /*in the child process*/
- sem_wait(&mutex);
- readFile.open("buffer.txt");
- //readFile.seekg(ios_base::beg);
- readFile >> aNum;
- readFile.close();
- aNum++;
- bufferFile.open("buffer.txt.", ios::out);
- bufferFile << aNum;
- bufferFile.close();
- childcount++;
- sem2 = 1;
- cout << "A. The number [ " << aNum <<"] modified by child\n";
- sem_post(&mutex);
- }
- else if(fork_return > 0 ) /*in the parent process*/
- {
- sem_wait(&mutex);
- readFile.open("buffer.txt");
- //readFile.seekg(ios_base::beg);
- readFile >> aNum;
- readFile.close();
- aNum++;
- bufferFile.open("buffer.txt.", ios::out);
- bufferFile << aNum;
- bufferFile.close();
- sem1 = 1;
- cout << "B. The number [ " << aNum <<"] modified by parent\n";
- sem_post(&mutex);
- }
- }//big while
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement