Mushtaq took 6 for 66 as South Africa, chasing 255 for victory, collapsed to 133 for 8 but an unbeaten ninth-wicket stand of 53 between Mark Boucher and Fanie de Villiers took South Africa to 186 for 8 at the close, 69 short of the target.
Mushtaq took four wickets in the afternoon session, including the 150th of his Test career, and after Waqar Younis dismissed the South African captain Hansie Cronje, Mushtaq had Shaun Pollock stumped and trapped Lance Klusener lbw.
Earlier, Pakistan resuming their second innings on 222 for 8, but lost their final two wickets in eight balls for four runs.
South Africa won toss; fourth day
PAKISTAN - First innings 259 (Azhar Mahmood 132; A A Donald 5-79).
SOUTH AFRICA - First innings 231 (S M Pollock 70no; Shoaib Akhtar 5-43).
PAKISTAN - Second innings
(Overnight: 222 for 8)
Mushtaq Ahmed run out 20
Shoaib Akhtar not out 1
Fazl-e-Akbar c Klusener b Pollock 0
Extras (w2, nb6, lb7) 15
Total (79.3 overs) 226
Fall (cont): 9-226.
Bowling: De Villiers 16-1-51-1 (nb2); Donald 10-2-20-1 (nb1, w2); Pollock 22.3-6-50-6 (nb1); Klusener 9-1-32-0 (nb2); Cronje 5-0-20-0; Kallis 17- 1-46-0.
SOUTH AFRICA - Second innings
G Kirsten c sub b Mushtaq 25
A M Bacher lbw b Fazl 0
J H Kallis c Moin b Mushtaq 22
H D Ackerman lbw b Mushtaq 11
A C Hudson c Fazl b Mushtaq 8
*W J Cronje c Moin b Waqar 11
S M Pollock st Moin b Mushtaq 30
M V Boucher not out 36
L Klusener lbw b Mushtaq 2
P S de Villiers not out 26
Extras (nb3 lb12) 15
Total (for 8) 186
Fall: 1-2 2-42 3-49 4-76 5-79 6-114 7-120 8-133
To bat: A A Donald.
Bowling: Waqar Younis 13-1-42-1 (nb3), Fazl-e-Akbar 5-2-16-1; Shoaib Akhtar 9-0-14-0; Mushtaq Ahmed 35-13-66-6; Azhar Mahmood 11-4-12-0; Aamir Sohail 7-1-24-0.
Umpires: M J Kitchen (Eng) and D L Orchard (SA).
Wasim Akram will join the team in South Africa ahead of the third Test at Port Elizabeth on Friday. The former Pakistan captain was left out of the original squad after allegations of betting and match-fixing.