(Adds Benghazi fighting, updates death toll)
By Ayman al-Warfalli
BENGHAZI, Libya Aug 14 (Reuters) - At least 42 people have been killed in clashes between Islamic State, a rival Islamist group and forces loyal to the official government in two Libyan cities, residents and medics said on Friday.
The fighting typifies the chaos in the oil-producing country, where two governments, former rebels and Islamist groups are battling for control, four years after the ousting of veteran ruler Muammar Gaddafi.
In the main eastern city, Benghazi, Islamic State attacked forces loyal to the official government. They killed five soldiers and destroyed a tank and three military vehicles, residents and medics said.
Seven soldiers were also wounded in the attack in the central area near the commercial port, closed for more than a year because of the fighting. A warplane could be heard later, as government forces brought in reinforcements.
In Sirte, a central city about 500 km (300 miles) east of the capital Tripoli, Islamic State fought with a rival Salafist Muslim group and armed residents who have been trying to expel it.
Islamic State fighters took over the city in February, expanding their presence in the North African country by exploiting a security vacuum, as they did in Iraq and Syria.
Fighting raged until early on Friday before dying down when Islamic State took back a district which the Salafists and armed residents had tried to seize, residents said.
Through the day the city was quiet, giving residents the chance to remove bodies strewn in the streets, among them women and children. Around 37 people have been killed in the past two days, residents said.
"Families are leaving Sirte," said a resident, asking, like others, not to be named. He said Islamic State fighters were searching for people with weapons.
A similar battle occurred in the eastern city of Derna in June when Islamic State was expelled by rival Islamist fighters who teamed up with locals angered by the arrival of foreign militants and clerics.
Islamic State launched an offensive to retake Derna this week.
Libya has two governments fighting each other for power, while Islamic State and other armed groups carve out their own fiefdoms.
The United Nations brought the main warring factions together in Geneva this week but the diplomacy has been overtaken by fighting between groups not present at the negotiating table. (Reporting by Ayman al-Warfalli; Writing by Ulf Laessing; Editing by Mark Trevelyan)
© Thomson Reuters 2015 All rights reserved