Fork() - Two processes accessing the same variable

Asked

Viewed 50 times

0

Why in the output he does only the multiplication that is requested in the parent process and does not the sum of the child process?

Entree:

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

int main(void) 
{
    int pvar = 1;
    printf("%d\n", pvar);
    pid_t childpid;
    childpid = fork();
    if (childpid == -1) 
    {
        perror("Errorr");
        return 1;
    }

    if (childpid == 0)
    { 
        pvar += 3;
        printf("I am child %ld\n", (long)getpid());

    }
    /* parent code */
    else
    { 
        pvar = pvar *4;
        printf("I am parent %ld\n", (long)getpid());
        printf ("Valor de pvar - %d\n", pvar);
        wait(0);
    }

    return 0;
}

Exit:

1
I am parent 10419
I am child 10420
4
  • The output does not match the code. Not to mention your code does not compile, at least two keys are missing

  • I edited the code, I had skipped a few lines on Ctrl c and I didn’t realize I jumped too.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.