Babar Azam scores sensational 122 while Mohammad Rizwan unbeaten 73 give Pakistan 2-1 lead.
Markram continues to impress at the top for the hosts, hitting his second fifty on the trot
Blazing half-centuries from Markram and Klaasen, and a fine spell from Shamsi, went in vain.
Mohammad Nawaz and debutant Usman Qadir shared four wickets after the batsmen took them to 320.
Rassie van der Dussen and Quinton de Kock also chip in with vital half-centuries in big batting effort.
Between a flinty century and a brilliant hundred, South Africa and Pakistan battled out in a last-ball thriller.