I run this prog. in foreground and background:
int main()
{
int pid;
printf("App Start pid=%d!\n",getpid());
while(1) {
pid=fork();
if(pid==0) {
printf("Child\n\n");
exit(0);
}
else if(pid>0) {
printf("Parent\n");
}
sleep(1);
}
}
in foreground:
$ ./fork
result is:
App Start pid=1360!
Parent
Child
Parent
Child
...
in background:
$./fork > out.txt &
$cat out.txt
App Start pid=1368!
Child
App Start pid=1368!
Parent
Child
App Start pid=1368!
Parent
Parent
Child
...
Why does the app 'restart' in background? I don't understand what happening. How can i make fork to work correctly in background app? Thanks