Archive for April, 2008

Unix Lucas Fork Program

April 05th, 2008 | Category: Coding

I wrote this program for a class a few semesters ago. It is a Lucas Number calculator that uses forks/pipes (a requirement of the project). Works great, hopefully it will help someone out there! It is also available for download below.


/* Lucas Fork & Pipe*/
#include <stdio.h>
#include <time.h> // to print the time

float fib(int); // fibonacci function, recursive
int fork(void);
void sleep(unsigned);

int main(void)
{
int n; // input variable
int i; // for the loop
int start = time(NULL); // get the time the process started
char buf[100]; /* store the characters read */

// pipe needs an integer array of size 2
int fd[2];
printf(”Create the pipe\n\n”);
pipe(fd); /* fd[0] read; fd[1] write */

printf(”Enter a number: “);
if (scanf(”%d”, &n) != 1) { // check to make sure there is input
printf(”Input error.\n”);
return 1;
}
printf(”Create the child process using fork\n”);
if (fork() == 0) { // child process
close(fd[1]); /* close write end */
printf(”child is running…\n”);
printf(”about to read from the pipe\n”);
n = read( fd[0], buf, 100); /* child reads from pipe */
printf(”after reading from the pipe\n”);
printf(”the value of n is: %d\n”,n);
printf(”the value in the buffer is: %s\n\n”, buf);
for (i = 0; i <= n; ++i) {
printf("fib(%2d) = %d\n", i, fib(i));
sleep(1);
}
}
else { // parent process
close(fd[0]); /* close read end - not needed for this example */
printf("parent is running...\n");
printf("about to write to the pipe\n");
write( fd[1], "Writing to pipe\n", n); /* parent writes to pipe */
printf("after writing to the pipe\n\n");
for (i = 0; i < n; ++i) {
sleep(1);
printf("Calculating...elapsed time = %d\n", time(NULL) - start);
}
}
return 0; // exits program
}

float fib(int n) // fibonacci function, recursive
{
if (n <= 1)
return n;
else
return (fib(n - 1) + fib(n - 2));
}

Lucas Fork Source File (zipped)

No comments