Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Operating Systems Homework 2 Fibonnaci Code by
- // Edmond Spike Snell
- // 2 . 20 . 2011
- #include <stdio.h>
- #include <stdlib.h>
- // main process to get command line argument and start child and parent process
- int main(int argc, char *argv[]) {
- // Initialize fibonacci array and pid_t and set values of first two fibonacci numbers
- int fib[48];
- fib[0] = 0;
- fib[1] = 1;
- pid_t pid;
- if(argc < 2 ) {
- printf("Enter how many numbers you want generated as an argument.\n");
- exit(0);
- }
- if(atoi(argv[1]) < 0 ) {
- printf("Argument must be a positive number.\n");
- exit(0);
- }
- if(atoi(argv[1]) > 47 ) {
- printf("Argument too large for integers, enter a smaller number\n");
- exit(0);
- }
- // this tries to start a fork process
- pid = fork();
- // if the fork fails exit with a code
- if(pid < 0) {
- fprintf(stderr, "The fork was a failure.\n");
- return 1;
- }
- // The child process runs here
- else if(pid == 0) {
- // start at the third fibonacci number
- int i = 2;
- // Handle the first three cases without generating more fibonacci numbers
- if (atoi(argv[1]) == 0) {
- printf("Fibonacci: ");
- }
- if (atoi(argv[1]) == 1) {
- printf("Fibonacci: 0 ");
- }
- if (atoi(argv[1]) == 2) {
- printf("Fibonacci: 0 1 ");
- }
- if (atoi(argv[1]) > 2) {
- printf("Fibonacci: 0 1 ");
- // Generate and print the remaining fibonnaci numbers
- while(i < atoi(argv[1])) {
- fib[i] = fib[i - 1] + fib[i - 2];
- printf("%d ", fib[(i)]);
- i++;
- }
- }
- printf("\n");
- }
- // The parent process runs here
- else {
- // Waiting for the child to complete
- wait(NULL);
- }
- // The parent and child process are done so exit the program
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement