Advertisement
Guest User

Untitled

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