I'm trying to write a program that creates a child process and then closes itself. I then need the child to remain connected to the terminal.
The child process is working as intended (waits for terminal input, then prints it out) until the parent closes . When the parent process is terminated the child no longer waits for input and the "fgets error" message is printed out in the terminal indefinitely.
This is strange, as it seems that after the parent terminated the stdin closed but stdout of the child remained connected to the terminal.
int main(){
int pid1;
pid1=fork();
if (pid1==-1){
perror("fork");
exit(EXIT_FAILURE);
}
if (pid1==0){
while(1){
char *data;
char *result;
result=fgets(data,100,stdin);
if (result!=NULL){
printf("%s\n",data);
}
else{
printf("fgets error\n");
sleep(1);
}
}
}
else
{
//The sleep below is for debugging purposes
sleep(5);
exit(EXIT_SUCCESS);
}
}
Is there a way to keep the stdin/stdout of the child process directed from/to the terminal after it's parent has terminated? Any help/explanation would be greatly appreciated.