fork() - Where does this output come from?

I know how forks work for the most part, however how is the variable *var getting to be '-1' in the loops?

Code:
main()
{
int* var = (int *) malloc(sizeof(int));
*var = 5;

pid_t pid = fork();

if (pid == 0) {
while (*var)-- > 0) sleep (1);
printf("I am the child, var=%d\n", *var);
}
while (*var > 0) sleep (1);
usleep(1);
printf("I am the parent, var=%d\n", *var);
}

Output:
I am the child, var=-1
I am the parent, var=-1
first, this doesn't compile (besides the missing includes, there is a syntax error in the first while loop).

With it all fixed, your child prints both messages. your parent loops forever.

try with more output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <stdlib.h>
#include <stdio.h>

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

int main()
{
    int* var = malloc(sizeof(int));
    *var = 5;

    pid_t pid = fork();

    if (pid == 0) {
        while( (*var)-- > 0) sleep (1);
        printf("I am the child, var=%d, pid = %d\n", *var, getpid());
    }

    while (*var > 0) 
    {
        printf("I am the real parent, var=%d, pid = %d\n", *var, getpid());
        sleep (1);
    }
    usleep(1);
    printf("I am not really the parent, var=%d, pid = %d\n", *var, getpid());
}
Last edited on
Sorry I meant to fix those for the post because the example code I'm using had the same errors that needed to be fixed.

Why is it running infinitely? It can print out that the value of *var is '-1' thus making it less than 0.

*note: the 'printf' statement should not be in the while loop, only the sleep statement.
Last edited on
The child says `I am the parent' and you believe it.


┬┐Is `var' pointing to a valid location in child?
Last edited on
1
2
3
4
5
while (*var > 0) 
    {
        printf("I am the real parent, var=%d, pid = %d\n", *var, getpid());
        sleep (1);
    }


You are not modifying *var anywhere in the loop. So it is obvious it will loop forever, because *var always == 5.
Last edited on
Topic archived. No new replies allowed.