Cain (10-3) broke a personal three-game winless streak with the performance, in which he allowed two runs overall, walked one and struck out six.
Then the Giants' bullpen took over, blanking the Astros the rest of the way. Jeremy Affeldt, Sergio Romo and Javier Lopez combined for two scoreless frames and Santiago Casilla recorded the final two outs for his 23rd save.
Posey provided RBI singles in the first and fifth innings and Brandon Belt notched the Giants' other RBI with a bases-loaded walk as San Francisco completed a three-game sweep of the Astros.
Combined with the Los Angeles Dodgers' loss to San Diego Sunday, the Giants extended their lead in the National League West to 1 1/2 games with the victory.
Bud Norris (5-7) was tagged with the loss after issuing six walks over six full innings.
Chris Johnson got the only RBI for Houston.