1

Considering the following code, when the parent is terminated, the stdin control is taken back by the shell and there is no way to see that the child process is running except through the "ps -e" command. Is there is any way to give the stdin control to the child process before the parent dies? I read some similar topics here, but non of them gives a solution to this issue. One has suggested to use "#cat | ./a.out" as a work around but I want a code level solution if there is any.

pid = fork();
if( pid == 0)
{
    while(1);
}
else
{
    //wait(&childstatus);
    printf("Hello From Parent\n");
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
MKSOI
  • 49
  • 5
  • What do you need this for? Can't you simply switch the processes and have the child die and the parent continue? – melpomene Nov 09 '15 at 08:02
  • The code is just an example, I do not need that for this code particularly. I am taking in general. If the parent has created a child and do some stuff then it is over while the child is still doing something else. How can the parent let its child own the control of stdin to complete its execution after the parent death without the parent waiting for the child to finish? Is there any way for that? – MKSOI Nov 09 '15 at 08:10
  • I found your question interesting, from this post one would guess that what you want is impossible http://stackoverflow.com/questions/8319484/regarding-background-processes-using-fork-and-child-processes-in-my-dummy-shel. However, reading further i also found this other one: http://unix.stackexchange.com/questions/152379/is-reparenting-from-the-shell-possible, about the prctl() command (from linux kernel 3.4), which extend the possibilities for child process, still not doing what you really would. – terence hill Nov 09 '15 at 08:58
  • That sounds good. If we can re-parent the child by the shell rather than the init process. But as you said, it is change nothing about the stdin ownership. Thanks – MKSOI Nov 09 '15 at 09:03
  • @user3480226 You cannot have the child be re-parented by the shell. Instead, have the parent `wait()` until the child is finished. – fuz Nov 09 '15 at 09:38
  • this what was @terence talking about as a new feature in Linux kernel 3.4 and above. I know that I can let the parent wait for the child. The wait() statement is commented in my code. I wonder whether we can have the child inherit the stdin after parent's death without parent waiting for the child – MKSOI Nov 09 '15 at 11:04

1 Answers1

2

Yes, this is the way shell works. If you don't want the shell take active process group, keep the parent alive.

Zang MingJie
  • 5,164
  • 1
  • 14
  • 27