Pakistan spinners Yasir Shah and Nauman Ali grabbed three wickets in the space of 10 runs shortly before the close to halt South Africa's fightback on the third day of the first Test in Karachi on Thursday.
It looked as though South Africa would end the day at parity after wiping out Pakistan's big 158-run first-innings lead, but Yasir struck twice and Nauman once to leave the tourists on 187-4 at the close, a lead of just 29 with six second-innings wickets in hand.
Nightwatchman Keshav Maharaj was unbeaten on two and skipper Quinton de Kock was yet to score.
"We will try to get South Africa out as soon as possible because the pitch will get difficult," said Yasir who took 3-53 from 24 overs of testing leg-spin.
"We have not won a Test for some time now, so we want to win this Test and the series."
Earlier, the Pakistan tail wagged effectively as they added a further 70 before South Africa could take their final two wickets.
Pakistan's 378 all out gave them a crucial first-innings lead of 220.
South Africa were off to a confident start with Aiden Markram and Dean Elgar defying Pakistan's attack, and were 37 without loss at lunch.
Elgar, in visible discomfort after being hit on the left hand by a rising delivery from pacer Shaheen Shah Afridi, was caught by diving wicketkeeper Mohammad Rizwan off Yasir for 29.
Markram then added 127 for the second wicket with Rassie van der Dussen and at 175-1, South Africa looked to be ready to take control.
But Yasir changed the scenario by dismissing Dussen for a solid 64, inducing him to pop up a soft catch for Abid Ali at silly mid-off. He then trapped Faf du Plessis leg-before on the back foot for 10.
In between, Markram pushed forward uncertainly to Nauman, offering another soft catch for Abid in the same position, as three wickets fell in the space of 33 balls.
Markram, who had a leg before decision overturned when he was on four and survived a chance to Babar Azam off Yasir on 27, had batted with some polish, hitting 10 crisp boundaries in his 74, his eighth Test fifty.
Both Yasir and Nauman will be major threats for South Africa on a fourth-day National stadium pitch which produced 14 wickets on day one, four on the second and six on the third.
In the morning Pakistan resumed on 308-8 but the tail frustrated the Protea bowlers who were looking to wrap up the innings quickly.
South Africa's 25-year-old pace spearhead Kagiso Rabada, playing in his 44th Test, bowled Hasan Ali for 21 to reach 200 wickets -- the eighth South African to reach the landmark in Test cricket.
Pakistan were 323-9 at that point, but Yasir and Nauman added 55 valuable runs for the final wicket.
Yasir, who scored a Test century in Australia in 2019, hit a six and four fours in his 38 not out, while debutant Nauman scored three boundaries before falling leg before to left-arm spinner Maharaj for 24.
Rabada with 3-70 and Maharaj, who took 3-90, were the pick of the South African bowlers.