when parent process close, how to close the child?

can someone provide an example, where if the parent process quits for any reason, then the child process will also close?

You have two options
1) Wait for the child.
2) Kill the child, then wait for the child.

Both mean the parent has to know what its children are.

if i have a child process going in a for loop doing a sleep command, there is no guarantee that it will die before the parent dies, but i know that eventually it will die, is it still safe to do this? or is it always better to kill the child before the parent dies?

You've kind of answered your own question. If you know it'll die eventually, why wouldn't it be safe to wait for it?

Killing it, of course may not be safe when it's doing anything more important than sleep().

It's perfectly safe to kill a process that's already dead though, so if the child absolutely must quit when main does, kill it. If it's already dead it won't matter and if it isn't, it'll die. (unless it blocks the signal.)