Re: UNEXPECTED result on MontaVista Linux
From: David Schwartz (davids_at_webmaster.com)
Date: 09/03/05
- Next message: Sagaert Johan: "how to get local ip address (not using ifconfig) ???"
- Previous message: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- In reply to: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- Next in thread: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- Reply: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sat, 3 Sep 2005 11:44:42 -0700
"kevin" <kthkevin@gmail.com> wrote in message
news:1125740566.889583.38850@o13g2000cwo.googlegroups.com...
Please don't top post.
>> 1) Call _exit in one side of the fork and exit in the other.
>> 2) Make sure the child's code doesn't run off the end into the parent
>> or
>> vice-versa. Best way is usually to call _exit in the child.
>for 1) and 2), I didnt quite catch you, so can you explain a little bit
>more in detail, or can you give me a little example.
When you call 'exit', it flushes buffers. When you call 'fork', you make
two copies of the current process. If there are any unflushed buffers,
calling 'exit' in both the parent and the child will flush them twice. So
standard practice is to call '_exit' in the child.
It is a bit dangerous to use standard I/O in the child. If you want to,
say, write to stdout in the child, you should flush stdout before the call
to 'fork'.
As for the child's code running off into the parent, I'm saying don't do
this:
switch(fork())
{
case -1: //error
fprintf(stderr, "Unable to fork\m");
exit(1);
case 0: // child
do_something();
default: // parent
do_something_else();
}
If you do this, and 'do_something' returns, the child will then be
running the code the parent was supposed to be running. So put an
'_exit(0);' after do_something returns.
>> 3) Memory changes made after the call to fork are not shared.
>for 3), if I can declare private variable in child? it seems wrong in C
>grammer.
I don't understand what you're saying. After the 'fork', the two
processes go their separate ways. The only thing they still share is their
file descriptors. So if you do this:
int i=0;
switch(fork())
{
case 0: // child
i++;
_exit(0);
default: // parent
sleep(2);
printf("i=%d\n", i);
}
It will always print zero. When the child increments 'i', it increments
its copy.
The name 'fork' is very appropriate. First you have one process, and
then you have two. But the two processes then go their separate ways, like
the roads after a fork.
DS
- Next message: Sagaert Johan: "how to get local ip address (not using ifconfig) ???"
- Previous message: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- In reply to: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- Next in thread: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- Reply: kevin: "Re: UNEXPECTED result on MontaVista Linux"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|