F
felixfix
Hi all,
I am just wondering if something is wrong with my program. What it
bascially does is to output a fibonacci sequence base on the
command-line output. If I give a 5, it will generate the first 5
fibonacci number. The problem is, I thought the parent process will
always go first, and so here I should get "0, 1, 1, 2, 3" But I ran the
program, it will give me "1, 2, 3, 0, 1", which is, the child process
ran first. Is there any way to make the parent goes first?
Thanks.
fix.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int param;
pid_t pid;
int i;
int fib_n_2 = 0;
int fib_n_1 = 1;
int fib_n;
if (argc != 2)
{
fprintf(stderr, "An integer parameter is required\n");
exit(-1);
}
param = atoi(argv[1]);
if (param < 0)
{
fprintf(stderr, "An integer > 0 is required\n");
exit(-1);
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
exit(-1);
}
else if (pid > 0) { /* Parent process */
switch(param)
{
case 0:
printf("0\n");
break;
case 1:
printf("0, 1\n");
break;
default:
printf("0, 1, ");
}
wait(NULL);
printf("end Fibonacci sequence...\n");
exit(0);
}
else if (pid == 0) { /* Child process */
/* HERE */
for (i = 2; i < param; i++)
{
fib_n = fib_n_1 + fib_n_2;
fib_n_2 = fib_n_1;
fib_n_1 = fib_n;
printf("%d, ", fib_n);
}
}
}
I am just wondering if something is wrong with my program. What it
bascially does is to output a fibonacci sequence base on the
command-line output. If I give a 5, it will generate the first 5
fibonacci number. The problem is, I thought the parent process will
always go first, and so here I should get "0, 1, 1, 2, 3" But I ran the
program, it will give me "1, 2, 3, 0, 1", which is, the child process
ran first. Is there any way to make the parent goes first?
Thanks.
fix.
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int param;
pid_t pid;
int i;
int fib_n_2 = 0;
int fib_n_1 = 1;
int fib_n;
if (argc != 2)
{
fprintf(stderr, "An integer parameter is required\n");
exit(-1);
}
param = atoi(argv[1]);
if (param < 0)
{
fprintf(stderr, "An integer > 0 is required\n");
exit(-1);
}
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork Failed\n");
exit(-1);
}
else if (pid > 0) { /* Parent process */
switch(param)
{
case 0:
printf("0\n");
break;
case 1:
printf("0, 1\n");
break;
default:
printf("0, 1, ");
}
wait(NULL);
printf("end Fibonacci sequence...\n");
exit(0);
}
else if (pid == 0) { /* Child process */
/* HERE */
for (i = 2; i < param; i++)
{
fib_n = fib_n_1 + fib_n_2;
fib_n_2 = fib_n_1;
fib_n_1 = fib_n;
printf("%d, ", fib_n);
}
}
}