At tea, Pakistan were 274-5 with Shafiq unbeaten on 114 for his fourth Test hundred while Misbah fell for 88 after frustrating South Africa during a fifth-wicket stand of 197 on the fourth day at Dubai stadium.
Adnan Akmal was the other unbeaten batsman on one as Pakistan still needed another 144 runs to avoid an innings defeat.
When it looked like Misbah would guide Pakistan towards safety he fell to a smart move by South African captain Graeme Smith, who brought on part-timer Dean Elgar to bowl.
Shafiq reached his hundred with a superb on-drive off Jean-Paul Duminy for his 11th boundary to complete his second hundred against South Africa. He had hit 12 fours and a six off 268 balls at tea.
The day began with the news that South Africa's Faf du Plessis had been fined 50 percent of his match fee on ball tampering charges by match referee David Boon of Australia.