I am assuming I am using this the wrong way, but the idea is for the command line argument to be the length of my fibonnaci serquence… however the way I am doing this, after 9 I am screwed… how can I resolve this issue?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */
int fibonacci(int n)
{
int first = 0;
int second = 1;
int total, i;
for (i=0;i<n;i++)
{
printf("%d\n", first);
total = first + second;
first = second;
second = total;
}
return 0;
}
int main(int argc, char *argv[])
{
/*Spawn a child to run the program.*/
pid_t pid=fork();
if (pid==0) { /* child process */
if(*argv[1] == 45){
printf("number invalid \n");
}else{
int number = *argv[1] - 48;
fibonacci(number);
}
}
else { /* pid!=0; parent process */
waitpid(pid,0,0); /* wait for child to exit */
}
return 0;
}
Command line arguments are strings; convert the strings to integers:
This gives you a default value (9), and the option to override it. More thorough checking would reject more than 1 argument, and negative or zero returns from
atoi():Note that key information is reported to help identify what went wrong. After 47 entries, you overflow a 32-bit signed integer.
Note that testing for errors from
strtol()et al properly is a moderately complex business if you have to accommodate any return value whatsoever. If you only need to accommodate the range that you can print Fibonacci numbers for, it is rather simpler.The repeated four lines of error handling rapidly gets irksome. I use a function like this instead:
This reduces the error reporting to one line per error, which is preferable to four lines. (My full system is more complex than that, by quite a margin — all else apart, it gets told the program name and reports it automatically. But that’s a workable starting point.)