By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,610 Members | 1,041 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,610 IT Pros & Developers. It's quick & easy.

Confusion over fork()

ilikesuresh
P: 47
Hi I wrote the following program

Expand|Select|Wrap|Line Numbers
  1. int main()
  2. {
  3.  //pid_t cpid,ppid;
  4.  unsigned int status;
  5.  if(fork() == 0){
  6.  printf("\nChild Process ID%d",getpid());
  7.   scanf("\nEnter The Status:%d",&status);
  8.  exit(status);
  9. }
  10.  else
  11. {
  12.  wait(&status);
  13.  printf("\nParent Process ID%d",getpid());
  14.  printf("\nChild exit status =%d\n",status > 8);
  15.  }
  16. }

when i executing the line
Expand|Select|Wrap|Line Numbers
  1. scanf("\nEnter The Status:%d",&status);
is not executing.
and then always it gives the child exit status 1
What is the reason for this one?
plz clarify me
Thanks
Sep 20 '07 #1
Share this Question
Share on Google+
4 Replies

pbmods
Expert 5K+
P: 5,821
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]
Oct 5 '07 #2

arne
Expert 100+
P: 315
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:

Expand|Select|Wrap|Line Numbers
  1. int main( void )
  2. {
  3.  
  4.     int status;
  5.  
  6.     if(fork() == 0) {
  7.  
  8.         printf("\nChild Process ID%d",getpid());
  9.         printf( "\nEnter the exit status: " );
  10.         scanf("%d",&status);
  11.  
  12.         exit(status);
  13.  
  14.     } else {
  15.  
  16.         wait(&status);
  17.  
  18.         printf("\nParent Process ID%d",getpid());
  19.         printf("\nChild exit status =%d\n", WEXITSTATUS(status));
  20.     }
  21.  
  22.     return 0;
  23. }
  24.  
HTH,
arne
Oct 7 '07 #3

P: 1
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
Nov 16 '07 #4

arne
Expert 100+
P: 315
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
Nov 18 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.