Glamorgan 550 for 5 dec (Lloyd 313*, Root 79) beat Derbyshire 253 (Dal 92, Came 64, Reece 56, Patel 5-68) and 273 (Madsen 77, du Plooy 66, van der Gugten 3-41, Harris 3-59) by an innings and 24 runs
Glamorgan survived a nervous morning to claim the innings-and-24-run victory over Derbyshire they needed to keep their chances of promotion alive.
Derbyshire showed some stubborn resistance, but batting through three sessions on a fourth-day wicket was always going to be a tall order. In the end they were 273 all out, thanks to Madsen, 77, and Leus du Plooy, 66.
Glamorgan's 24-point haul means they will go into the final game in Sussex with a chance of promotion still alive, while Derbyshire will entertain Leicestershire with only local pride to play for.
Dark and cloudy conditions gave way to bright sunshine just before the start of play, Glamorgan would have been happier with the heavy atmosphere as they struggled to make the early breakthrough.
Du Plooy and Madsen played out the early overs easily enough and it came as a bit of a surprise when the South African shouldered arms to a ball from Hogan which nipped back and hit off stump.
It has been a wicket where new batsmen have struggled on occasion and so it proved for Harry Came, who was quickly lbw to Ajaz Patel.
Yet while Dal was at the wicket with Madsen there was no complacency among Glamorgan players or supporters, until Harris came up with the big breakthrough in a burst after lunch.
He was close to having Dal lbw, an inside edge saving the batter, but next ball the edge was not his friend as a snick carried to wicketkeeper Chris Cooke to expose the Derbyshire tail.
That started a burst of three wickets in 11 balls which effectively made Glamorgan's win just a matter of time. Andrew Salter had Alex Thomson lbw for a second duck in the match, then Harris struck again to take the key wicket of Madsen, who played on trying to steer the ball down to third.
There was a brief flourish at the end from Sam Connors, getting his highest score of the season of 23 before hooking Hogan to Timm van der Gugten at long leg.
In the end Glamorgan wrapped up their sixth victory of the season to keep their interest alive going into the final round of fixtures.
James Harris makes crucial breakthroughs as Glamorgan keep promotion hopes alive
Hosts overcome nervous morning to claim innings win over Derbyshire in Cardiff
Ajaz Patel five-wicket haul helps Glamorgan close in on victory over Derbyshire
Hosts need another seven wickets on final day as they chase promotion
David Lloyd 313 not out makes more towering history for Glamorgan
Highest score ever made by a Welshman leaves Derbyshire facing a long haul to safety