How to terminate correctly program?