Search code examples
linuxdebiancccollatz

How to properly use if else statements and while loops with a child process in C


I'm new to C and I've been trying to create a program that takes a user input integer makes a sequence depending on whether the number is even or odd.

n / 2 if n is even

3 * n + 1 if n is odd

A new number will be computed until the sequence reaches 1. For example if a user inputs 35:

35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1

For some reason my code doesn't work after the scan statement of the child process. I left my code and sample output below:

Code:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main()
{
pid_t pid;

    int i = 0;
    int j = 0;
    /* fork a child process */
    pid = fork();


    if (pid < 0) { /* error occurred */
        fprintf(stderr, "Fork Failed\n");
        return 1;
    }
    else if (pid == 0) { /* child process */
        printf("I am the child %d\n",pid);


    printf("Enter a value: \n");
    scanf("%d", i);

    while (i < 0) {
        printf("%d is not a positive integer. Please try again.\n", i);
        printf("Enter a value: \n");
        scanf("%d", i);

    }
    // can add a print i here
    while (i != 1) {

        if (i % 2 == 0) { // if the inputted number is even  
            j = i / 2;      
        }

        else {
            j = 3 * i + 1;
        }
    printf("%d", j);    
    } 

}


    else { /* parent process */
        /* parent will wait for the child to complete */
        printf("I am the parent %d\n",pid);
        wait(NULL); // wait(NULL) will wait for the child process to complete and takes the status code of the child process as a parameter

        printf("Child Complete\n");
    }

    return 0;
}

Output I'm getting on terminal in Linux (Debian):

oscreader@OSC:~/osc9e-src/ch3$ gcc newproc-posix.c 
oscreader@OSC:~/osc9e-src/ch3$ ./a.out
I am the parent 16040
I am the child 0
Enter a value: 
10
Child Complete
oscreader@OSC:~/osc9e-src/ch3$

Solution

  • Transferring comments into a semi-coherent answer.

    Your calls to scanf() require a pointer argument; you give it an integer argument. Use scanf("%d", &i); — and it would be a good idea to check that scanf() returns 1 before testing the result.

    My compiler told me about your bug. Why didn't your compiler do so too? Make sure you enable every warning you can! Your comment indicates that you're using gcc (or perhaps clang) — I routinely compile with:

    gcc -std=c11 -O3 -g -Werror -Wall -Wextra -Wstrict-prototypes …
    

    Indeed, for code from SO, I add -Wold-style-declarations -Wold-style-definitions to make sure functions are declared and defined properly. It's often a good idea to add -pedantic to avoid accidental use of GCC extensions.

    In the loop, you don't need j — you should be changing and printing i instead.

    cz17.c

    #include <stdio.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    int main(void)
    {
        int i = 0;
        pid_t pid = fork();
    
        if (pid < 0)
        {
            fprintf(stderr, "Fork Failed\n");
            return 1;
        }
        else if (pid == 0)
        {
            printf("I am the child %d\n", pid);
    
            printf("Enter a value: \n");
            if (scanf("%d", &i) != 1)
            {
                fprintf(stderr, "failed to read an integer\n");
                return 1;
            }
    
            while (i <= 0 || i > 1000000)
            {
                printf("value %d out of range 1..1000000. Try again.\n", i);
                printf("Enter a value: \n");
                if (scanf("%d", &i) != 1)
                {
                    fprintf(stderr, "failed to read an integer\n");
                    return 1;
                }
            }
    
            while (i != 1)
            {
                if (i % 2 == 0)
                {
                    i = i / 2;
                }
                else
                {
                    i = 3 * i + 1;
                }
                printf(" %d", i);
                fflush(stdout);
            }
            putchar('\n');
        }
        else
        {
            printf("I am the parent of %d\n", pid);
            int status;
            int corpse = wait(&status);
            printf("Child Complete (%d - 0x%.4X)\n", corpse, status);
        }
    
        return 0;
    }
    

    Compilation:

    gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes cz17.c -o cz17 
    

    Sample output:

    $ cz17
    I am the parent of 41838
    I am the child 0
    Enter a value: 
    2346
     1173 3520 1760 880 440 220 110 55 166 83 250 125 376 188 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2 1
    Child Complete (41838 - 0x0000)
    $