I know that they could re-surface to re-establish a normal supply of air but what about when they were under attack and couldnt surface for long periods of time,wouldnt those engines use up a lot of the oxygen inside the sub?
Either the submarine remained close to the surface with a pipe (snorkel) supplying air, or they stopped the diesel engine and relied on batteries. Some experiments were made where the submarine would bring oxidizer (oxygen or sometime oxygen peroxide) in tanks. But of course the supply was limited.
Water is H2O they use and used a process where they take the water and filter out the hydrogen leaving them with oxygen and they just pump out the hydrogen into the ocean
Diesel submarines that were used during WWII actually have two different types of engines. The main Diesel engine, and an electric one. When a boat submerges they use the electric engines only, these usually only have an hour or so worth of power. Once they resurface they fire up the diesel. They are stuck on the surface until the electric engines are re-charged by the diesel. Prior to the advent of the nuclear submarine (which can remain submerged almost indefinitely), the submarine spent most of its time on the surface like any other ship.
As others have stated the diesel engines could be used under water only with a snorkle system which wasn't very practical to do if you were indeed under attack. The have ports at the engine room to take in combustion air (oxygen) and to exhaust the combustion gases. The generator/motor was built inline with the drive shaft to the main propeller. As the diesel engine powered the prop it used the generator/motor to charge a bank of batteries. When the sub went under the diesel engines were shut off and the sub was powered by the battery bank. There is a huge switch station just to the rear of the engine room for this purpose.