Help needed with fork operation

This is a discussion on Help needed with fork operation within the C Programming forums, part of the General Programming Boards category; Code: #include<stdio.h> #include<stdlib.h> main(void) { if(fork()) {//parent process printf("Parent process\n"); printf("par:%d\n",getpid()); } else {//child process printf("Child process\n"); printf("Child :%d Parent:%d\n",getpid(),getppid()); ...

  1. #1
    Registered User
    Join Date
    Nov 2011
    Posts
    32

    Help needed with fork operation

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    main(void)
    {
        if(fork())
        {//parent process
            printf("Parent process\n");
            printf("par:%d\n",getpid());
        }
        else 
        {//child process
            printf("Child process\n");
            printf("Child :%d    Parent:%d\n",getpid(),getppid());
        }
    }


    When we use fork() function, a child process is created. In this case what will status of 'program counter' of a child process (when started).

    I know that the child process contains the code of else block,but I don't know why it is so.

    Code:
    #include<stdio.h>
    #include<stdlib.h>
    main(void)
    {
    printf("ID:%d\n",getpid());
        if(fork()==0)
        {//exclusively child is created?
        printf("par:%d    child:%d\n",getppid(),getpid());
        }
    }
    In the above code, how the contents of the if block belongs to a child process.

  2. #2
    Registered User
    Join Date
    Oct 2011
    Location
    Denmark
    Posts
    80
    Upon successful completion, fork() shall return 0 to the child process and shall return the process ID of the child process to the parent process
    That's why the code in the if block is executed by the child process, but not by the parent. Does it answer your question?
    HomePort : A C Web Service API for heterogeneous home automation systems

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help needed on parallel processing using fork() in C
    By smithu.simi in forum C Programming
    Replies: 7
    Last Post: 03-27-2009, 08:15 AM
  2. i get illegal operation.
    By entry_point in forum C++ Programming
    Replies: 4
    Last Post: 10-02-2007, 10:41 PM
  3. new operation
    By NewGuy100 in forum C Programming
    Replies: 3
    Last Post: 07-28-2005, 11:45 AM
  4. Is this considered an AND operation?
    By Unregistered in forum C Programming
    Replies: 9
    Last Post: 07-22-2002, 03:40 PM
  5. illegal operation
    By jdinger in forum Windows Programming
    Replies: 3
    Last Post: 04-07-2002, 08:14 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21