Thread: Parent and Child Processes

  1. #1
    Registered User
    Join Date
    Feb 2016
    Posts
    1

    Question Parent and Child Processes

    I'm trying to understand how child and parent processes work....this is my output.

    Child0Parent0
    ChildParent10

    Child2
    Parent0

    Child3
    Parent0

    Child4
    Parent0

    Can anyone tell me why Parent isn't incrementing? My code is below:

    Code:
    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <string.h>
    
    
    char mynum='0';
    int main(void)
    {
        int i;
        pid_t fork_return;
        static char buffer[10];
        fork_return = fork();
        if (fork_return == 0)
        {
            strcpy(buffer, "CHILD"); 
            for (i=0; i<5; ++i) 
            {
                mynum=i + '0';
                sleep(1); 
                write(1, buffer, sizeof(buffer));
                write(1, &mynum, 1);
                write(1, "\n", 1);
            }
            return 0;
        }
        else
        {
            strcpy(buffer, "PARENT"); 
            for (i=0; i<5; ++i) 
            {
                sleep(1); /*5 times each*/
                write(1, buffer, sizeof(buffer));
                write(1, &mynum, 1);
                write(1, "\n", 1);
            }
            return 0;
        }
    }
    Last edited by rogeroneilyoung; 02-25-2016 at 11:23 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Because after the fork(), both processes have unique copies of all variables.

    Incrementing a variable in the child has no effect in the parent.

    You need proper shared memory for this to happen.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 05-01-2011, 11:06 AM
  2. Parent and child processes program variables
    By tfarmer4 in forum Linux Programming
    Replies: 1
    Last Post: 03-01-2011, 05:36 PM
  3. Forking child processes form parent to exec commands
    By Imanuel in forum C Programming
    Replies: 3
    Last Post: 08-02-2010, 09:03 AM
  4. Trouble understanding parent and child processes
    By cardinals03 in forum C++ Programming
    Replies: 11
    Last Post: 10-04-2009, 05:51 PM
  5. Sighandler questions with child/parent processes
    By ninjacookies in forum C Programming
    Replies: 2
    Last Post: 07-05-2005, 06:38 AM