Mohammad Rizwan scored a first Test century as Pakistan set South Africa a daunting target of 370 to win the second and final Test in Rawalpindi, but the tourists closed the fourth day on 127 for one to set up an intriguing finale.
Rizwan was unbeaten on 115 and batted brilliantly with the tail to help add 222 for the final five wickets as the home side were bowled out for 298 in their second innings, profiting from a number of dropped catches by the visitors.
Aiden Markram (59 not out) and Rassie van der Dussen (48 not out) gave South Africa hope after adding an 94 for the second wicket, showing the patience and application that will be needed on the final day if they are to claim an unlikely victory.
South Africa have not made over 300 in the fourth innings to win a Test since their remarkable 414 for four against Australia in Perth in 2008, while the highest successful run chase ever in Pakistan is 315 for nine by the home side, against Australia, in 1994.
The only wicket to fall was opener Dean Elgar (17), who edged to wicketkeeper Rizwan chasing a wide delivery from seamer Shaheen Afridi.
But the pitch is still good for batting and has not yet shown prodigious turn for the spinners, leaving South Africa in with a sniff on the fifth day.
They would have been chasing considerably less had they not dropped a number of catches, including off Rizwan when he had four.
Instead the latter was the anchor for the Pakistan second innings as they resumed the fourth day on 129 for six.
They lost Hasan Ali (5) early, lbw to Keshav Maharaj (3-118), before Rizwan put on 53 with Yasir Shah (23) and 97 for the ninth wicket with Nauman Ali (45).
The innings was over when left-arm spinner George Linde (5-64) bowled Shaheen (4) for his first test five-wicket haul, a remarkable effort given a horrific injury to the small finger on his bowling hand on the opening day that left bone protruding from the wound.
South Africa had spoken overnight of hoping to chase around 250, but Pakistan's tail ensured it would be substantially more than that.
Pakistan won the first Test in Karachi by seven wickets.