/* File: ftdemo.cpp */ /* Demonstrate file tables. Open a file, fork, open it again. */ /* Show when system file table entries are shared, and when */ /* they aren't */ /* Test some std I/O stuff */ #include #include #include #include #include using namespace std; main() {int inward,inout; // file descriptors char ch; // Fill a file with numbers, say 1000 digits inout=open("abc.txt",O_RDWR|O_CREAT|O_TRUNC); for (int k=0;k<1000;k++) { char z=(char)(k%10+48); write(inout,&z,sizeof(char)); if (k%80==79) { ch='\n'; write(inout,&ch,sizeof(char)); } } lseek(inout,0,SEEK_SET); // back to start pid_t IsParent; IsParent=fork(); if (IsParent) { read(inout,&ch,sizeof(char)); cout << "Parent reads " << ch << " from shared stream\n"; wait(NULL); cout << "wait() Returns!\n"; } else { sleep(1); // let parent go first read(inout,&ch,sizeof(char)); cout << "Child reads " << ch << " from shared stream and closes it\n"; close(inout); cout << "Original Data file:\n"; system("cat abc.txt"); cout << endl; inward=open("abc.txt",O_RDONLY); cout << "Child opens new stream on same file and reads 10 characters:\n"; for (int j=0;j<10;j++) { read(inward,&ch,sizeof(char)); cout << ch; } cout << endl; inout=open("abc.txt",O_RDWR); cout << "Child writes the upper case alphabet to start of file\n"; for (int jj=0;jj<26;jj++) { char p=(char)(jj+65); write(inout,&p,sizeof(char)); } cout << "Child writes the lowcase alphabet to 50th spot of file, using cerr\n"; lseek(inout,50,SEEK_SET); dup2(inout,2); for (int jj=0;jj<26;jj++) { cerr << (char)(jj+97); } close(inout); cout << "Data file:\n"; system("cat abc.txt > /dev/tty "); // what is /dev/tty?? cout << endl; cout << "Now, read next 10 chars via new stream (not formerly shared one)\n"; for (int n=0;n<10;n++) { read(inward,&ch,sizeof(char)); cout << ch; } cout << endl; } }