ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
Ok here i have a program thats supposed to compute the fibanocci sequence with a child & parent process. Does everything it is supposed to do but when i do ./fibMem X where X > 7, it cuts off the last two numbers. So my output for ./fibMem 9 is:
Ok, Child is done!
*1123581234
What am i doing wrong? and can i have spaces between so its easier to read instead of printing everything in one line?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/stat.h>
#define max_sequence 10
typedef struct{
long fib_sequence[max_sequence];
int sequence_size;
}shared_data;
void main(int argc, char *argv[])
{
pid_t pid;
int status;
int m = 0;
long oldnum = 1;
long curnum = 1;
long nextnum, i;
int num_counter = 0;
char* shmem;
int segment;
shared_data *sdptr;
shared_data sd;
int temp;
if(argc < 2){
printf("Invalid Number of Arguments\n");
exit(0);
}
else
i = atoi(argv[1]);
i =i - 1;
if(i < 2 || i > max_sequence)
{
printf("Invalid Number \n");
exit(2);
}
sd.sequence_size = i;
segment = shmget(IPC_PRIVATE, sizeof(sd), S_IRUSR | S_IWUSR);
shmem = (char*) shmat(segment, NULL, 0);
switch(pid = fork())
{
case -1:
perror("Fork Failed \n");
break;
case 0:
sprintf(shmem, "%d%c ", oldnum, ' ');
num_counter++;
while(i > 0)
{
shmem++;
sprintf(shmem, "%d ", curnum);
nextnum = curnum + oldnum;
oldnum = curnum;
curnum = nextnum;
i--;
}
printf("\n");
exit(1);
default:
wait(&status);
printf("Ok, Child is done! \n");
printf("*%s \n", shmem);
break;
}
}
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.