COmputer science...COMPUTER SCIENCE Module: 207SE Operating Systems, Security and Networks User:...
Transcript of COmputer science...COMPUTER SCIENCE Module: 207SE Operating Systems, Security and Networks User:...
COMPUTER SCIENCE
Module: 207SE Operating Systems, Security and
Networks
User: Jubad Miah [email protected]
StudentID: 6375364
Portfolio 1
Lab Activity 1 – Operating Systems Tasks and Programming
a) Future of operating systems.
An operating system is the most significant software that runs on a computer. It manages the computer's processes and memories, as well as all its software and hardware. It also allows you to communicate with the computer without knowing how to speak the computer's language. Without an operating system, a computer is impractical. The future of operating systems may become more
efficient and most powerful with combined operating systems soon. Some says the sky is the limit and I believe there is no limit to progress and accomplish better technologies.
b) Programming activity
Commented code below:
1. agent=["bot", "mike"] 2. direction=["forward", "backward", "left", "right"] #saves words as there types 3. objects=["nut", "plum", "cat", "cup"] 4. action=["pick", "put", "lift", "drop", "go"] 5. pronoun=["i", "you", "we"] 6. colour=["red", "blue"] 7. 8. sentance= input("please type sentence: ") #take input from user 9. sentance = sentance.lower() #makes everything lowercase 10. words = sentance.split() #splits string at each whitespace into list 11. 12. structure1=["age", "act", "obj"] 13. structure2=["age", "act", "col", "obj"] 14. structure3=["age", "act", "dir"] 15. structure4=["pro", "act", "obj"] 16. structure5=["pro", "act", "dir"] #defines the correct grammer rules 17. 18. ls=[] #create a new list 19. 20. for i in range(len(words)): #for loop to go through each word in input string 21. if words[i] in agent: #match a word with its type 22. ls.append("age") #append age (meaning agent) to the new list 23. continue 24. elif words[i] in direction: 25. ls.append("dir") 26. continue 27. elif words[i] in objects: 28. ls.append("obj") 29. continue 30. elif words[i] in action: 31. ls.append("act") 32. continue 33. elif words[i] in pronoun: 34. ls.append("pro") 35. continue 36. elif words[i] in colour: 37. ls.append("col") 38. continue #output will be a list like ["age", "act", "obj"] 39. 40. 41. if ls == structure1: #match ls with a grammer rule, if it matches then print
correct 42. print ("This is Correct! (age-act-obj)") 43. elif ls == structure2: 44. print ("This is Correct! (age-act-col-obj)") 45. elif ls == structure3:
46. print ("This is Correct! (age-act-dir)") 47. elif ls == structure4: 48. print ("This is Correct! (pro-act-obj)") 49. elif ls == structure5: 50. print ("This is Correct! (pro-act-dir)") 51. else: 52. print ("This is Incorrect!......Try Again ") #if it doesnt match then print
incorrect
Outcomes from the code below (two examples proven)
Lab Activity 2 – Linux Command Line (Commands and outcomes from a series
of small tasks that require use of a number of Linux commands)
a) How made Portfolio1 directory read/write/executable only for you and your
group. That is, not for others. Show evidence of this with ls command. Linux command: chmod 771 Portfolio1
Evidence:
b) How downloaded the script http://www.centerkey.com/tree/tree.sh to your home directory using wget and make it executable.
Linux command: wget then chmod +x tree.sh then:./tree.sh
Evidence below:
wget:
chmod +x tree.sh
./tree.sh
c) Making Directories
How to create a 207se directory in your Portfolio1 directory.
Linux command: mkdir 207se
How to create numbered directories for the labs. i.e. lab1 and lab2 etc.
Linux command: mkdir Lab1 then again mkdir Lab2
Evidence of make directory activities using ./tree.sh
d) Display todays date and using the cal command show the month that you were
born. For today’s date: cal or date
For my birth month: cal 4 April 1990 Evidence:
e) Move into the lab1 directory and use the appropriate command to show the
current directory Linux command: cd portfolio1 then cd 207se then cd Lab1 then ls Evidence:
f) what is talk, write and wall are for??
Write does just that. Writes what you type (ending the message with a "Ctrl-D") to the
terminal of the user you want to send a message to. It is one-way.
Talk will try to connect to a users terminal to start a two-way conversation. It uses the
curses library to control the screens (terminals) used in the connection.
wall is "write to all" one way communication to all logged in users. It is how the "shutdown message" is sent when root uses shutdown (1m) to change the run level of a system.
g) What command prevents the effects of those three commands from
interrupting you. Linux command: mesg n Evidence:
h) The song in song.txt.
Using wc the number of words and lines in the file. Linux command: wc song.txt
Using grep to get the lines containing "and" and the number of the lines contain “and” in the document Linux command: egrep -n ‘and’ song.txt Evidence:
Use cat to show the contents of the file. Linux command: cat song.txt Evidence:
Open the song.txt file with a text editor and randomly replace any two words with your first and second names and save the file as song_name.txt. Use the appropriate Linux command to see if the two files differ and how they differ.
Linux command: diff song.txt song_name.txt Evidence:
Use sort to sort the file and redirect the output to a new file called song2.txt Linux command: sort song.txt > song2.txt Evidence:
Use sort and rev to reverse the sorted contents of song.txt and append the output to song2.txt Linux command: sort -r song.txt > song2.txt
Evidence:
Total memory used and the total memory available
Linux command: free -m Evidence:
Find out how you can display your username on the screen. Linux command: echo ‘SUSER’ Evidence:
List the processes that are running. Linux command: ps aux Evidence:
What are the differences between the Linux commands less, more and most.
More is a filter for paging through text one screen full at a time,
Less is a program similar to more but it allows backward movement in the file as
well as forward
Most is a paging program that displays one windowful at a time.
Lab Activity 4 Bootloader
a) Brief description of the Lab activity and what you did
In this activity we were required to boot pragma linux with bochs, then make a bootloader that displays your name, email address, your favourite second year module, date of birth, age and student number on a separate lines also we are required to make bootloader that displays triangle of dots to get full marks for this activity.
b) Boot pragma linux with bochs Linux command: bochs
c) Make a bootloader that displays your student details and triangle
Commented bootloader code to display your student details and triangle Source code and comments below:
1. [BITS 16]
17. mov si, studentID //move studentID variable into si
18. call writeString //call writeString to print si
19. mov dx,10 //move 10 into data segment (dx)
20.
21. outer_loop: //outer loop function
22. mov cx,10 //move 10 into cx
23. inner_loop: //inner loop function
24. mov si, triangleOfDots //move variable star into si to print
25. call writeString //print si
26. dec cx / /decrement si
27. cmp cx,dx //compare cx with dx
28. jge inner_loop //gets back to start of inner loop
29. mov si,newLine //this newLine variable starts a new line simple
30. call writeString //prints newLine 31. dec dx //decrement dx
32. cmp dx,0 //compare dx to 0
33. jne outer_loop //if dx is not 0 then go back to outer_loop
34. jmp $ //if dx same as 0 then its completed 35. 36. writeString:
37. mov ah,0x0E //prints antyhing that is in si
38. mov bh,0x00
39. mov bl,0x07
40.
41. nextchar:
42. Lodsb // Loads [si] into AL and increases si by one 43. // Effectively "pumps" the string through AL
44. cmp al,0 // End of the string?
45. jz done //jump if 0
46. int 0x10 // BIOS interrupt
47. jmp nextchar //jump to nextchar 48.
49. done:
2. [ ORG 0 x 7C00] ;Where the code gets mapped 3. top: 4. mov ax,0x0000 5. mov ds,ax //data segment 6. mov si, HelloWorld //move HelloWorld variable into si 7. //si is the location relati ve to the data segment of the string/char to display
. 8. call writeString //call writeString function to print si ( see below) 9. mov si, email 10. call writeString 11. mov si, module 12. call writeString 13. mov si, dob 14. call writeStrin g 15. mov si, age 16. call writeString
50. ret
51. HelloWorld db 'Name: Jubad Miah',13,10,0 ; Null-terminated
52. //putting the words 'Hello World' in memory location HelloWorld 13, 10 -
start a new line
53. //0 used to check for end of string
54.
55. email db 'Email: [email protected]',13,10,0 //storing string in to email
56. module db 'Favourite 2nd Year Module: Operating Systems, Security and Networks'
,13,10,0 //storing string into module 57. dob db 'Date of Birth: 23/04/1990',13,10,0 //storing string into dob
58. age db 'Current Age: 26',13,10,0 //storing string into age 59.
60. studentID db 'Student ID: 6375364',13,10,0 //storing string into studentID
61. triangleOfDots db '*',0 //store '*' in star 62. newLine db '',13,10,0 //store string starting a newLine 63. times 510-($-$$) db 0 //$$ start of program
64. dw 0xAA55 //bootloader signature (backwards)
Output from Bochs showing student details and triangle
What happens if we replace jmp $ with jmp top… the answer is simple it will loop
forever. (linux evidence below)
Lab Activity 6 Memory Management
a) Memory Allocation Activities
1. First-Fit memory allocation method:
2. Repeat the same activity as above but for the best-fit and worst-fit methods.
Once you have done the allocation approach yourself use the exe code by
typing ./best-fit then ./worst-fit.
Best-Fit method:
Worst-Fit methods:
3. Which are the approaches allocates all of the processes and with the least
fragmentation?
First-fit total free memory: 250 Best-fit total free memory: 220 Worst-fit total free memory: 350
Portfolio Activities
1. Using the first-in-first-out paging approach, complete the paging table below
showing how pages will be swapped in and out of main memory for a paging table
with limits of 3 or 4 table entries. Determine the page fault total.
Paging Accessing Sequence: 42775639322
Three table page entries:
4 2 7 7 5 6 3 9 3 2 2
Page Entry 0 4 4 4 4 5 5 5 9 9 9 9
Page Entry 1 2 2 2 2 6 6 6 6 2 2
Page Entry 2 7 7 7 7 3 3 3 3 3
Page Fault * * * * * * * *
Page Fault Total: 8
Linux results: screenshot below shows the final 2 stages:
Four table page entries:
4 2 7 7 5 6 3 9 3 2 2
Page Entry 0 4 4 4 4 4 6 6 6 6 6 6
Page Entry 1 2 2 2 2 2 3 3 3 3 3
Page Entry 2 7 7 7 7 7 9 9 9 9
Page Entry 3 5 5 5 5 5 2 2
Page Fault * * * * * * * *
Page Fault Total: 8
Linux Result: screenshot below shows the final 2 stages:
Run the fifi exe file (./fifo) is the result the same? Yes I believe it is the same by
looking at the screenshots provided above.
2. Repeat the above process for the random page allocation approach.
Paging Accessing sequence: 42775639322
Three table page entries:
4 2 7 7 5 6 3 9 3 2 2
Page Entry 0 4 4 4 4 4 4 4 4 4 2 2
Page Entry 1 2 2 2 5 6 3 9 9 9 9
Page Entry 2 7 7 7 7 7 7 3 3 3
Page Fault * * * * * * * * *
Page Faults Total: 9
Linux results: Screenshot below shows random memory allocation:
Four table page entries:
4 2 7 7 5 6 3 9 3 2 2
Page Entry 0 4 4 4 4 4 6 6 9 9 9 9
Page Entry 1 2 2 2 2 2 2 2 2 2 2
Page Entry 2 7 7 7 7 7 7 7 7 7
Page Entry 3 5 5 3 3 3 3 3
Page Fault * * * * * * *
Page Fault Total: 7
Linux results: Screenshot below shows random memory allocation:
Run the random exe file (./random) is the result the same. If not why not?? Basically, it generates random memory allocation and it won’t be the same all the time.
Lab Activity 7 Buffer
a) Brief description of the Buffer Activity
This week we will look at a simple buffer approach to copy a file from one location to another using a buffer. Like when you are using YouTube to watch videos. The code that is provided needs editing so it works to complete this week’s lab activity.
b) Commented Buffer.c code
38. }
c) Update the code to so that it prints if an error has occurred or if a file is successfully created with the content of the review in it. After running code what is in hamlet.txt
Updated code below:
28. printf("Unable to write to given file\n");
// prints error message 3
29. exit(3); 30. }
31.
32. while (rd_size > 0) {
33.
34. rd_size = read(in_fd, buf, BUF_SIZE); //repeatedly read from original
file into buffer
35. if (rd_size <0) {
36. printf("Nothing to be read in the file.\n"); //prints error message 4
37. exit(4);
38. }
39. wr_size = write(out_fd, buf, rd_size); //repeatedly write from buffer to
new fi le
40. if (wr_size<=0){
41. printf("Successfully created the file!\n"); //prints error message 5
42. close(in_fd); //if there is nothing to write then close input file
43. close(out_fd); //close files
44. exit(5);
45. }
46. }
47. }
Linux Output:
d) Updated buffer.c code to show how many characters are read to buffer, how
many character read at a time into the buffer, how many words in the document
and how many times the buffer is filled
Commented updated code here to count characters, count words and to read how many
times buffer filed:
1. #include < fcntl.h > //defines the .h files 2. #include < stdlib.h > 3. #include > unistd.h < 4. #include < stdio.h > 5. 6. #define BUF_SIZE 500 //define buffer si ze and set permissions 7. #define OUTPUT_MODE 0700 8. 9. int main( int argc, char *argv[]) //this is the main function 10. { 11. int in_fd, out_fd; //defines variables
30. out_fd = creat(argv[2], OUTPUT_MODE); //creates file
58. }
Output of code:
e) Impact of changing buffer size
Buffer count changes to ‘2’ when buffer size moved up to 2000.
Random change of buffer size to ‘30’ which changes buffer count to 114.
f) Updated buffer.c code to compare if two files are the same
Updated code with added function:
1. #include <fcntl.h> //defines the .h files
2. #include <stdlib.h>
3. #include <unistd.h>
4. #include <stdio.h>
5.
6. #define BUF_SIZE 500 //define buffer size and set permissions
7. #define OUTPUT_MODE 0700
8.
9. int goCompare(char *c_File) //This is a new function to goCompare two files
10. {
11. int content1, content2; //list of defined variables
12. char goC_File[50];
13. int rd_size1 = 1, rd_size2 = 1;
14. char buffer_one[BUF_SIZE];
15. char buffer_two[BUF_SIZE];
16. int i, x=0; 17. char p;
18.
19. printf("please enter the name of the txt file to goCompare with: "); //user
ente rs the name of another file to with
20. scanf("%s", goC_File); //usually read
21. content1 = open(goC_File, O_RDONLY); //opens the file requested
22. content2 = open(c_File, O_RDONLY); //this opens the file
created i n the main
23.
24. if (content1 < 0)
25. exit(printf("There is nothing in the given file!\n")); //prints and exits
if nothing given
26.
27. while (rd_size1 > 0) { //while characters in the text file
28.
29. rd_size1 = read(content1, buffer_one, BUF_SIZE); //sets both read size
t o bytes and puts 500 characters in buffer as defined
30. rd_size2 = read(content2, buffer_two, BUF_SIZE);
31.
32. if (rd_size1 <0)
33. exit(printf("Nothing to be read in file.\n"));
34. if (rd_size2 <0)
35. exit(printf("Nothing to be read in file2\n")); //this
statement checks if there is anything to be read
36.
37. for (i = 0;i<rd_size1;i++){ //for loop to loop through buffer
38. p = buffer_two[i];
39. if (buffer_one[i] != p) { //checks characters in both buffer
40. if (x == 0)
41. printf("The file differs in the following ways: \n"); //prints st
79. }
80.
81. while (rd_size > 0) {
82. filled = filled + 1;
83. rd_size = read(in_fd, buf, BUF_SIZE); //repeatedly read from original
file into buffer
84. characters = rd_size + characters;
85. for (counter = 0; counter < rd_size; counter ++) {
86. if (buf[counter] == ' '){
87. word = word + 1;
88. }
89. }
90. if (rd_size <0) {
91. exit(4);
92. }
93. wr_size = write(out_fd, buf, rd_size); //repeatedly write from buffer
to new fi le
94. if (wr_size<=0){
95.
96. printf("Successfully created the file!\n"); //prints the statement file crea ted
97. printf("buffer count %d\n", filled); //prints how many times the buff er is filled
98. printf("Character count: %d\n", characters); //prints how many characters are read from the buffer at a time
99. printf("Amount of words in file: %d\n", word); //prints how many words are in t he document
100. printf("how many words read in the document: %d\n", word);
101.
102. //compare files
103. printf("Do you want to goCompare with another txt file [y/n]? "); //asks user to enter yes or no to continue with comparing another file
104. scanf("%s", buf);
105. if (buf[0] == 'y')
106. goCompare(argv[2]);
107. close(in_fd); //close files
108. close(out_fd); //close files
109. exit(5);
110. }
111. }
112. }
Comparison of review.txt and hamlet.txt:
Comparison of hamlet.txt and review_observer.txt:
Lab Activity 8 Cache Buffer
a) Brief Description of Cache Buffer Activity
In the weeks activity we are required to create cache library which will read a certain amount of the files contents into a buffer referenced in the cr_file struct. My exercise is to type up code for cr_read_byte function which is basically a cache reader which read character by character at a time and print on the screen.
b) Commented implementation of the cr_read_byte function
Comment code of the cr_read_byte function:
File cache_reader.c -> char cr_read_byte
1. char cr_read_byte(cr_file* f){ //this cr_read_byte function orequests a by te from the file represented by the cr_file pointer
2. //it returns the next byte in that structur 's buffer (char is one byte)
3. if (f->usedbuffer == f-
>bufferlength) //if statement checks if the buffer is empty
4. {
5. refill(f); //refill variable
6. }
7. char tmprary = f->buffer[f->usedbuffer++]; //used buffer temporary access
8. f- >usedbuffer++; it current pos
//incrementing index usedbuffer and moves ition along one by one
9. return (tmprary); //this just returns successive bytes f
rom the relevant cr_file buffer
10. return EOF; //returns and makes the compile work p roperly
Output of running code below:
Source code with nominal changes to the library code
1. //------------------------------------------------------------------
2. char cr_read_byte(cr_file* f){ //this cr_read_byte function orequests
a by te from the file represented by the cr_file pointer
3. //it returns the next byte in that structur 's buffer (char is one byte)
4. if (f->usedbuffer == f-> bufferlength) //if statement checks if the buffer is
empty
5. {
6. printf(" buffer is being filled\n"); //advance task code here,
prints statement and new line.
7. refill(f); //refill variable
8. }
9. printf(" -byte is being read\n"); //advance task code here
10. char tmprary = f->buffer[f->usedbuffer++]; //used buffer temporary access f->usedbuffer++; //incrementing index usedbuffer
and moves it current position along one by one
12. return (tmprary); rom the relevant cr_file buffer
//this just returns successive bytes f
13. return EOF; //returns and makes the compile work p
roperly
14. }
Changes to main program: cache_example.c
1. #import "cache_reader.h"
2.
3. //changes to main program
4.
5. int main(){
6. char c; //assigned variables
7. int cCount = 0;
8. int bufferCount=0;
9. int numWord = 0;
10. //Open a file
11. cr_file* f = cr_open("text",20); //opens cr_file
12. while((c=cr_read_byte(f)) !=EOF) ound
{ //while loop to show the char bytes being f
13. cCount = cCount + 1; //calculates the characters.
14. printf("%c", c);
15.
16. //if statement to if the buffer is empty or full 17. if (f->usedbuffer==f->bufferlength) //if statement to show the word count
taking place 18. bufferCount = bufferCount+1; //counts how many times the buffer
being filled one by one
19. if ((f->buffer[f->usedbuffer])==' ') //statement to check if buffer is
empty
20. numWord = numWord +1; //counts the number of words in the
file
21. }
22. printf("\n"); //prints newline
23. printf("number of numWords in the file: %d\n", numWord);
//prints the number of words in the file
24. printf("number of characters: %d\n", cCount);
//prints the number of characters in the file
25. printf("number of times the buffer is being filled: %d\n",bufferCount);
//prints the number of times the buffer is being filled
26.
27. //ends the program
28. cr_close(f);
29.
30. return 0;
31.
32. }
Advance Tasks 2
Provide some statistics in the cache_example.c code to show how many bytes were read in
total, how many words were read in and how many times the buffer was refilled.
Screenshot below shows the linux evidence:
Lab 10: The Cache Buffer from week 8 with system calls
a) Brief description of the activity
In this lab, we have been asked us to change the cache_reader library from
using the fopen, fread, fclose functions to the system call versions open, read,
close
For the advanced task, we had to change the code and adapt so that the effects
of caching on the library is as far as possible meaning decreasing the cache
usage to minimal.
b) Changes the cache_reader library from using the fopen, fread, fclose functions
to the system call versions open, read, close
Commented code outlining changes to the .h file:
1. #include <stdio.h> 2. #include <stdlib.h> 3. 4. //The internals of this struct aren't important 5. //from the user's point of view 6. typedef struct{ 7. int file; //File being read, reads as ASCII 8. int bufferlength; //Fixed buffer length 9. int usedbuffer; //Current point in the buffer 10. char* buffer; //A pointer to a piece of memory 11. // same length as "bufferlength" 12. } cr_file; 13. 14. //Open a file with a given size of buffer to cache with 15. cr_file* cr_open(char* filename, int buffersize); 16. 17. 18. //Close an open file 19. void cr_close(cr_file* f); 20. 21. //Read a byte. Will return EOF if empty. 22. char cr_read_byte(cr_file* f); 23. 24. //---------------------------------------------------------
25. 26. //Refill an empty buffer. Not intended for users 27. int refill(cr_file* buff);
Commented code outlining changes to the .c file:
1. #include "cache_reader.h" 2. #include <sys/types.h> 3. 4. //http://www.phim.unibe.ch/comp_doc/c_manual/C/SYNTAX/struct.html 5. //http://vergil.chemistry.gatech.edu/resources/programming/c-
tutorial/structs.html 6. 7. int refill(cr_file* buff){ //refill variable 8. if(buff->usedbuffer!=buff-
>bufferlength) //if statement to check iff buffer is empty or full 9. return 0; 10. else{ 11. buff->usedbuffer=0; 12. int len=read(buff->file, buff->buffer, buff-
>bufferlength); //read only buffer, fill up EOF 13. 14. if(len<buff->bufferlength) 15. for(int i=len;i<buff->bufferlength;i++) 16. buff->buffer[i]=EOF; // EOF access 17. return len; 18. } 19. 20. } 21. 22. void cr_close(cr_file* f){ 23. 24. free(f->buffer); 25. close(f->file); 26. } 27. 28. cr_file* cr_open(char * filename, int buffersize){ 29. char buff[buffersize=512]; 30. FILE* f; 31. if ((f = open(filename, O_RDONLY|O_DIRECT)) ==-
1 ) { //opened for reading only, format for open O_DIRECT is used to reduce the caching from/for a file
32. fprintf(stderr, "Cannot open %s\n", filename); 33. return 0; 34. } 35. 36. cr_file* a=(cr_file*)malloc(sizeof(cr_file)); 37. a->file=f; 38. a->bufferlength=buffersize; 39. a->usedbuffer=buffersize; 40. a->buffer=(char*)memalign(sizeof(char)*buffersize, sizeof(char)*buffersize); 41. refill(a); 42. return a; 43. } 44. 45. //------------------------------------------------------------------ 46. char cr_read_byte(cr_file* f){ //this cr_read_byte function requests from the file
represented by the cr_file pointer 47. //it returns the next byte in that structur 's buffer (char is one byte) 48. if (f->usedbuffer == f-
> bufferlength) //if statement checks if the buffer is empty 49. { 50. printf(" buffer is being filled\n"); //advance task code here, 51. refill(f); //refill variable
52. } 53. printf(" byte is being read\n"); //advance task code here 54. char tmprary = f->buffer[f-
>usedbuffer++]; //incrementing index usedbuffer and moves it current position along one by one
55. return f->buffer[f->usedbuffer++]; //this just returns successive bytes from the releveant cr file
56. 57. return EOF; //returns and makes the compile works 58. }
Output from running code here:
c) Changes cache_reader library to remove (as far as possible) the effects of
caching on the library.
cache_reader.c
1. #define _GNU_SOURCE //allowed access to other functions 2. #include "cache_reader.h" 3. #include <sys/stat.h> 4. #include <fcntl.h> 5. #include <unistd.h> 6. #include <sys/types.h> 7. 8. //http://www.phim.unibe.ch/comp_doc/c_manual/C/SYNTAX/struct.html 9. //http://vergil.chemistry.gatech.edu/resources/programming/c-
tutorial/structs.html 10. 11. int refill(cr_file* buff){ //refill variable 12. if(buff->usedbuffer!=buff-
>bufferlength) //if statement to check iff buffer is empty or full 13. return 0; 14. else{ 15. buff->usedbuffer=0; 16. int len=read(buff->file, buff->buffer, buff-
>bufferlength); //read only buffer, fill up EOF 17. 18. if(len<buff->bufferlength) 19. for(int i=len;i<buff->bufferlength;i++) 20. buff->buffer[i]=EOF; // EOF access 21. return len; 22. } 23. 24. } 25. 26. void cr_close(cr_file* f){ 27. 28. free(f->buffer); 29. close(f->file); 30. } 31.
32. cr_file* cr_open(char * filename, int buffersize){ 33. char buff[buffersize=512]; 34. FILE* f; 35. if ((f = open(filename, O_RDONLY|O_DIRECT)) ==-
1 ) { //opened for reading only, format for open O_DIRECT is used to reduce the caching from/for a file
36. fprintf(stderr, "Cannot open %s\n", filename); 37. return 0; 38. } 39. 40. cr_file* a=(cr_file*)malloc(sizeof(cr_file)); 41. a->file=f; 42. a->bufferlength=buffersize; 43. a->usedbuffer=buffersize; 44. a->buffer=(char*)memalign(sizeof(char)*buffersize, sizeof(char)*buffersize); 45. refill(a); 46. return a; 47. } 48. 49. //------------------------------------------------------------------ 50. char cr_read_byte(cr_file* f){ //this cr_read_byte function requests from the file
represented by the cr_file pointer 51. //it returns the next byte in that structur 's buffer (char is one byte) 52. if (f->usedbuffer == f-
> bufferlength) //if statement checks if the buffer is empty 53. { 54. printf(" buffer is being filled\n"); //advance task code here, 55. refill(f); //refill variable 56. } 57. printf(" byte is being read\n"); //advance task code here 58. char tmprary = f->buffer[f-
>usedbuffer++]; //incrementing index usedbuffer and moves it current position along one by one
59. return f->buffer[f->usedbuffer++]; //this just returns successive bytes from the releveant cr file
60. 61. return EOF; //returns and makes the compile works 62. }
cache_example.c
1. #import "cache_reader.h" 2. //changes to main program 3. int main(){ 4. char c; //assigned variables 5. int cCount = 0; 6. int bufferCount=0; 7. int numWord =0; 8. 9. //Open a file 10. cr_file* f = cr_open("text",20); //opens cr_file 11. 12. while((c=cr_read_byte(f)) !=EOF) { //while loop to show the char bytes being f 13. bufferCount = bufferCount + 1; //ccalculates how many times the buffer b
eing filled 14. printf("%c", c); 15. 16. //if statement to if the buffer is empty or full 17. if (f->usedbuffer==f-
>bufferlength) //if statement to show the word count taking place 18. cCount = cCount +1; //calculates the characters 19. if ((f->buffer[f->usedbuffer])==' ') //statement to check if buffer is empty 20. numWord= numWord +1; //counts the number of words in the file 21. }
22. printf("\n"); //prints newline 23. printf("number of characters: %d\n", cCount); //prints the number o
f characters in the file 24. printf("number of buffer being filled: %d\n", bufferCount); //prints the number o
f times the buffer is being filled 25. printf("Total words read in the file: %d\n", numWord); //prints the number o
f words in the file 26. cr_close(f); //ends the program 27. return 0; 28. 29. } 30.
cache_reader.h
1. #include <stdio.h> 2. #include <stdlib.h> 3. 4. //The internals of this struct aren't important 5. //from the user's point of view 6. typedef struct{ 7. int file; //File being read, reads as ASCII 8. int bufferlength; //Fixed buffer length 9. int usedbuffer; //Current point in the buffer 10. char* buffer; //A pointer to a piece of memory 11. // same length as "bufferlength" 12. } cr_file; 13. 14. //Open a file with a given size of buffer to cache with 15. cr_file* cr_open(char* filename, int buffersize); 16. 17. 18. //Close an open file 19. void cr_close(cr_file* f); 20. 21. //Read a byte. Will return EOF if empty. 22. char cr_read_byte(cr_file* f); 23. 24. //--------------------------------------------------------- 25. 26. //Refill an empty buffer. Not intended for users 27. int refill(cr_file* buff);
Evidence / Output of the above codes.
References
What are the differences between most, more and less?. "What Are The Differences
Between Most, More And Less?". Unix.stackexchange.com. N.p., 2017. Web. 25 Feb.
2017.
Gite, Vivek. "Linux Commands For Shared Library Management & Debugging
Problem". Cyberciti.biz. N.p., 2017. Web. 29 Feb. 2017.
"What Is Linux?". Linux.com | The source for Linux information. N.p., 2017. Web. 2
Mar. 2017.
"Linux Commands". Mediacollege.com. N.p., 2017. Web. 1 Mar. 2017.