Dale Steyn and Kagiso Rabada both took four wickets to get South Africa to the brink of victory.
Steyn drew level with Richard Hadlee of New Zealand in tenth place on 431 wickets on the all-time Test wicket-takers list.
Masood and Shafiq shared the most enterprising partnership of the match when they put on 132 in 132 minutes off 168 balls for the third wicket.
Steyn broke the stand when Masood was caught behind by wicketkeeper Quinton de Kock and Philander followed up having Shafiq caught behind after a sparkling innings in which he hit 12 fours and a six in facing 118 balls.
Shafiq had looked set to make his second century in successive appearances at Newlands after he made 111 in the 2012/13 fixture between the two countries.
A mini-collapse followed but Azam batted well with the tail in scoring 72 off 87 balls.
Azam was ninth out, caught at first slip off Rabada when Pakistan were only 16 runs ahead 15 minutes before the scheduled close.
A second successive win for South Africa inside three days seemed likely when Mohammad Abbas was caught off Philander seven minutes and eight runs later when the extra half hour would have been enough to finish the match.
But after checking a replay, Philander was no-balled and Abbas and last man Shaheen Afridi took the game into a fourth day.
Article source: https://sports.ndtv.com/cricket/south-africa-vs-pakistan-pakistan-avoid-innings-defeat-delay-south-africa-victory-charge-1973218