Confusion over fork()

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ilikesuresh
    New Member
    • Aug 2007
    • 47

    Confusion over fork()

    Hi I wrote the following program

    [code=c]int main()
    {
    //pid_t cpid,ppid;
    unsigned int status;
    if(fork() == 0){
    printf("\nChild Process ID%d",getpid()) ;
    scanf("\nEnter The Status:%d",&sta tus);
    exit(status);
    }
    else
    {
    wait(&status);
    printf("\nParen t Process ID%d",getpid()) ;
    printf("\nChild exit status =%d\n",status > 8);
    }
    }[/code]


    when i executing the line
    [code=c]scanf("\nEnter The Status:%d",&sta tus);[/code] is not executing.
    and then always it gives the child exit status 1
    What is the reason for this one?
    plz clarify me
    Thanks
    Last edited by pbmods; Oct 5 '07, 06:49 PM. Reason: Added CODE tags.
  • pbmods
    Recognized Expert Expert
    • Apr 2007
    • 5821

    #2
    Heya, ilikesuresh.

    You posted this in the Articles section. I'll go ahead and move it to the Forum where an Expert will be more likely to find it.

    Please use CODE tags when posting source code:

    [CODE=c]
    Source code goes here.
    [/CODE]

    Comment

    • arne
      Recognized Expert Contributor
      • Oct 2006
      • 315

      #3
      The code line is executed, only the result is not what you expect :)

      A look into the man page of wait reveals that the status returned by wait is storing status information about the child. Among this info you can also find the exit status, but this information has to be extracted by a macro. Try the following:

      [CODE=c]
      int main( void )
      {

      int status;

      if(fork() == 0) {

      printf("\nChild Process ID%d",getpid()) ;
      printf( "\nEnter the exit status: " );
      scanf("%d",&sta tus);

      exit(status);

      } else {

      wait(&status);

      printf("\nParen t Process ID%d",getpid()) ;
      printf("\nChild exit status =%d\n", WEXITSTATUS(sta tus));
      }

      return 0;
      }
      [/CODE]

      HTH,
      arne
      Last edited by pbmods; Oct 7 '07, 01:44 PM. Reason: Changed [CODE] to [CODE=c].

      Comment

      • cmstvm
        New Member
        • Nov 2007
        • 1

        #4
        data sharing in process

        hello,
        i am Anish here.I have a doubt.If we change any variables in the process ,is it visible for the parent?
        expecting replay
        regards
        Anish

        Comment

        • arne
          Recognized Expert Contributor
          • Oct 2006
          • 315

          #5
          Originally posted by cmstvm
          hello,
          i am Anish here.I have a doubt.If we change any variables in the process ,is it visible for the parent?
          expecting replay
          regards
          Anish
          No, they are not visible.

          arne

          Comment

          Working...