I am working on a project which needs relay to be controlled using raspberry pi. I have set up my script to run on boot up but when power is turned off sometimes the relay is left in ON state as the program exits mid way which is not desired. Is it possible to terminate an auto run script safely once power is switched off?
is there a way to safely shut down pi on power off as the abrupt power off may corrupt my SD card or even damage my pi.
You might want to invest in special power supply like that power supply but it is expensive. It is the only certain way to save your device from power outages long enough for them to shutdown. It could be cheaper to buy something like that battery power supply, and try to switch to it when power dies down. Some circuit with transistor blocking power consumption from batteries while normal power supply is supported. You would need then breadboard power supply to power your PI and switch between power supplies. You could also connect some GPIO pin to alternate power supply to detect when it switched and initialize safe shutdown.
But you also said "no extra circuit". Only way to do that would be to add startup script to restart whatever services need to be restarted on startup. Just check if they have properly shut down and if not - shut them down before you start them again.