Advertisement
Guest User

Untitled

a guest
Jul 27th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.73 KB | None | 0 0
  1. // Operating Systems Homework 2 Fibonnaci Code by
  2. // Edmond Spike Snell  
  3. // 2 . 20 . 2011
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7.  
  8. // main process to get command line argument and start child and parent process
  9. int main(int argc, char *argv[]) {
  10.  
  11.   // Initialize fibonacci array and pid_t and set values of first two fibonacci numbers
  12.   int fib[48];
  13.   fib[0] = 0;
  14.   fib[1] = 1;
  15.   pid_t pid;
  16.  
  17.   if(argc < 2 ) {
  18.     printf("Enter how many numbers you want generated as an argument.\n");
  19.     exit(0);
  20.   }
  21.  
  22.   if(atoi(argv[1]) < 0 ) {
  23.     printf("Argument must be a positive number.\n");
  24.     exit(0);
  25.   }
  26.  
  27.   if(atoi(argv[1]) > 47 ) {
  28.     printf("Argument too large for integers, enter a smaller number\n");
  29.     exit(0);
  30.   }
  31.  
  32. // this tries to start a fork process
  33. pid = fork();
  34.  
  35. // if the fork fails exit with a code
  36. if(pid < 0) {
  37.   fprintf(stderr, "The fork was a failure.\n");
  38.   return 1;
  39. }
  40.  
  41.  
  42. // The child process runs here
  43. else if(pid == 0) {
  44.  
  45.   // start at the third fibonacci number
  46.   int i = 2;
  47.  
  48.   // Handle the first three cases without generating more fibonacci numbers
  49.   if (atoi(argv[1]) == 0) {
  50.     printf("Fibonacci: ");
  51.   }
  52.   if (atoi(argv[1]) == 1) {
  53.     printf("Fibonacci: 0 ");
  54.   }
  55.   if (atoi(argv[1]) == 2) {
  56.     printf("Fibonacci: 0 1 ");
  57.   }
  58.  
  59.   if (atoi(argv[1]) > 2) {
  60.  
  61.     printf("Fibonacci: 0 1 ");
  62.  
  63.     // Generate and print the remaining fibonnaci numbers
  64.     while(i < atoi(argv[1])) {
  65.  
  66.       fib[i] = fib[i - 1] + fib[i - 2];
  67.       printf("%d ", fib[(i)]);
  68.       i++;
  69.  
  70.     }
  71.   }
  72.  
  73.   printf("\n");
  74.  
  75. }
  76.  
  77.  
  78. // The parent process runs here
  79. else {
  80.  
  81. // Waiting for the child to complete
  82. wait(NULL);
  83.  
  84. }
  85.  
  86. // The parent and child process are done so exit the program
  87. return 0;
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement