You can "force quit" apps... several ways to do this.
Command + Option + Esc on your keyboard or click your Apple menu icon top left in your screen. From the drop down menu click Force Quit.
Or, using the Activity Monitor located in /Applications/Utilities
Once you have force quit Safari you can shut down your Mac.
Hi if safari does not quit then you can try many things, here is a list
1) Force quit by holding the keys (CMD+Q)
2) if step 1 did not work then click on the apple logo at the top left of your screen then go to force quit then highlight safari then click on force quit.
3) this should work its called Force Shut down, simple hold down the power button for about 5 seconds then you imac will force itself to shut down, if none of the above worked leave a reply.