I am trying to create a Collatz structure that asks the user how many times they would like to run it. Then it loops the code incrementing each time by 3 (n = n + 3). While the code partially works, it continues to repeat the previous process that is finished, e.g. with an input of 5 and running the process 3 times "Child 1 = 5, 16, 8, 4, 2, 1" and "Child 2 = 8,4,2,1" and "Child 3 = 11,34,17,52,26,13,etc."
The issue is, it is looping too many times and running each Child multiple times. One time it is correct and the second time it runs it, it starts the sequence at "1."
I am running this from a Linux Debian. To compile I use "gcc -o filename filename.c" and then to execute I use "./filename 5" where 5 is the number passed to "n" for the Collatz structure. Then it prompts how many times to run the loop.
I understand I am probably way off, but I am completely lost and would greatly appreciate any assistance.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
pid_t pid;
int n, j, x;
printf ("How many times would you like this to run?\n");
scanf ("%d",&j);
if (argc == 1) {
fprintf (stderr,"Usage: ./a.out <starting value>\n");
return -1;
}
printf("\nMain program's process ID: %d\n",getpid());
n = atoi(argv[1]);
for (x=1; x <= j; x++){
pid = fork();
if (pid < 0) {
fprintf(stderr, "Unable to fork child\n");
return -1;
}
else if (pid == 0) { /*child process */
printf("\nChild %d (ID: %d)\n",x,getpid());
printf("\nStart sequence at: %d\n",n);
while (n != 1) {
n = n % 2 ? 3 * n + 1 : n / 2;
printf("\n(Child %d) %d ",x,n);
}
printf("\n\nAbout to end execution (I'm process %d) .\n",getpid());
}
else { /* parent process */
wait(NULL);
n = n + 3;
}
}
return 0;
}