I'm going to assume you're talking about the US since you mention the executive, judicial and legislative branches. As a non-US citizen this might be slightly off and most of my knowledge is gained from watching episodes of Stargate, but I think I've gained an understanding of how it works over the years as well. Someone else will probably come along with a better answer, but if they don't, you have this.
Primarily the people are the ones who stop a military coup from happening- the second amendment was put in place for that very reason, so the people could wrest control from the government if the military took over and the people objected. But in practice, I think the military personnel would have a problem with it as well. For ongoing military control, there are civilian oversight committees that report to the people that control the budget, so if they see anything they don't like, either it gets changed or they can't afford to do it anymore.
In the US, the government isn't accountable to the military, it's accountable to the people. They're the ones who can change things if they don't like where they're going. If the government as a whole became so corrupt something drastic had to be done, well, I imagine that as well would be an issue for the people to resolve.
Other countries have their own methods of dealing with this. The UK, where I live, has a monarch that isn't really part of the government as such and controls the military- the government acts with her permission so if they refused to step down she'd use the military to force them down. She has control over the other Commonwealth militaries as well, so she could do the same for Australia, Canada, New Zealand etc.
So in general it's about money/resources, which is generated by the civilians. Their representatives fund the military if they're good, and if they're not, hire someone else and give them the money/resources instead.