C process printing twice after fork() even though it's inside the parent process and I flush stdout

Viewed 182

I'm working on a C project for school that involves using shared memory but I can't seem to figure out why the parent process is printing the results twice after the fork. I flush the stdout after the print, but it still prints twice.

Heres my code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/mman.h>
#include <semaphore.h>
#include <fcntl.h>

/* Defining system macros to avoid magic numbers */
#define TRUE 1
#define FALSE 0
#define MEM_SIZE sizeof(collatz_data)
#define NAME "OS"
#define SEQ_SIZE 50

/* A data struct that will be put into the shared memory to store our values */
typedef struct {
    int starting_number;
    int sequence[SEQ_SIZE];
    int seq_count;
    int is_finished;
} collatz_data;

/* Function for calculating the collatz formula */
int calculate_collatz(int n) {
    return (n % 2 == 0) ?  (n / 2) : (3 * n + 1);
}

/* Shared memory passing project main run loop */
int main(int argc, char *argv[]) {
    
    int shm_fd;
    pid_t pid;
    collatz_data *shared_memory;
    
    /* Requirement 1: Check to see if the number passed on the command line is positive */
    if (argv[1] <= 0) {
        printf("The number you entered was not positive.\n Exiting program...\n");
        exit(1);
    }
    
    /* Getting the number from the command line using atoi function to turn character into int */
    int number = atoi(argv[1]);
    
    printf("\n");
    
    /* Create the shared memeory segment & configure it's size*/
    shm_fd = shm_open(NAME, O_CREAT | O_RDWR, 0666);
    ftruncate(shm_fd, MEM_SIZE);
    
    /* Map the shaerd memory segment to this address space */
    shared_memory = mmap(0, MEM_SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);
    
    /* Check to see that our shared memory segment was mapped correctly */
    if (shared_memory == MAP_FAILED) {
        printf("Map Failed\n");
        return -1;
    }
    
    
    /* Fork the current process and create a child */
    fflush(stdout);
    pid = fork();

      /* Check if the fork failed */
      if ((pid=fork()) == -1) {
          perror("Fork Failed");
          
          /* Kill the program */
          exit(1);
      }

     // Child
     else if (pid == 0) {

         int i = 0;
         int n = shared_memory->starting_number;
         
         /* Make the first number in the sequence the number from the command line */
         shared_memory->sequence[i++] = n;
         
         /* Calculate the collatz sequence by storing the numbers in our shared memory sequence */
         while (n != 1 && i < SEQ_SIZE) {
             n = calculate_collatz(n);
             shared_memory->sequence[i++] = n; // Store the next number
         }
         
         /* Store the size of our sequence so the parent can loop over this number later to print it out*/
         shared_memory->seq_count = i;

         // Kill the child process
         exit(0);
     }
      
      // Parent
         else if (pid > 0) {
             
             /* Requirement 2: Pass the input from the command line to the child process */
             shared_memory->starting_number = number;
             
             /* Requirement 4: Inoviking wait will the child calculates the sequence */
             wait(NULL);
             
             printf("Collatz Sequence for number (%d): \n", number);

             /* Requirement 5: Print out collatz results generated by the child */
             for (int i = 0; i < shared_memory->seq_count; i++) {
                 printf("%d ", shared_memory->sequence[i]);
             }
             printf("\n");
             fflush(stdout);
             
             exit(0);
         }
    
     /* Remove the shared memory object */
     shm_unlink(NAME);

    return 0;
}

The output should be:

Collatz Sequence for number (99): 99 298 149 448 224 112 56 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

But for some reason that entire thing gets printed twice. Any ideas of what I'm doing wrong? Thanks.

1 Answers

Figured this one out.

Changed this:

if ((pid=fork()) == -1) {
      perror("Fork Failed");
      
      /* Kill the program */
      exit(1);
  }

To This:

if (pid == -1) {
      perror("Fork Failed");
      
      /* Kill the program */
      exit(1);
 }

Turns out I had an entire other process running this exact same code. After removing that the problem was solved.

Related