#include #include #include #include #include using namespace std; void Parent(int file); void Child(int file); int main() { int file; //int flags{O_CREAT | O_RDWR | O_DIRECT | O_TRUNC}; int flags{O_CREAT | O_RDWR | O_TRUNC}; char c; srand(time(nullptr)); mode_t perms{S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH }; // open a file and write the alphabet. file = open("alphabet", flags, perms); for( int i =0; i < 26; ++i) { c = static_cast('A' + i); write(file, &c, sizeof(char)); cout << "Writign a " << c << endl; } // now fork pid_t pid {fork()}; if (pid == -1) { perror("Fork Faild"); exit(0); } if (pid == 0) { Child(file); } else { int status; Parent(file); wait(&status); } return 0; } void Parent(int file){ // open the pipe for reading. // when we successfully read anything from the pipe // seek to 0 // print the position. int pipeFD = open("mypipe", O_RDONLY); char c; int numread; ssize_t pos; while ((numread = read(pipeFD, &c, sizeof(char))) > 0) { cout << "Parent: I am checking the file" << endl; pos = lseek(file, 0, SEEK_CUR); read(file, &c, sizeof(char)); cout << "Parent: The offset is currently at " << pos << endl; cout << "Parent: Just got a " << c << " from the file" << endl; cout << endl; } return; } void Child(int file){ int pipeFD = open("mypipe", O_WRONLY); int len; char x{'a'}; len = lseek(file,0, SEEK_END); cout << "Child: The file length is " << len << endl; for(int i = 0; i < 3; ++i) { size_t offset = rand() % len; // tell the user what is up. cout << "Child: Iteration " << i << endl; cout << "Child: seeking to " << offset << endl; cout << "Child: writing a " << x << endl; // do the action lseek(file, offset, SEEK_SET); write(file, &x, sizeof(char)); // back up one so the other proc reads the x lseek(file, -1, SEEK_CUR); x = static_cast(x + 1); cout << endl; // tell the other proc to move on. write(pipeFD, &x, sizeof(char)); sleep(1); } }