The pair put on 139 for the sixth wicket as the tourists, resuming at 118-5 and still 182 runs behind Sri Lanka's first innings total of 300, moved to 390-8 by tea on the scheduled fourth day.
Shafiq was unbeaten on 115, his seventh Test century and the third in the last four matches following his 137 against New Zealand in Sharjah and 107 against Bangladesh in Dhaka.
Tailender Zulfiqar Babar proved the surprise packet, slamming a career-best 51 not out off 52 balls while adding 88 for the unbroken ninth wicket.
Sarfraz, a wicket-keeper who relishes a challenge with the bat, scored 96 off 86 balls in a rousing knock that was studded with 13 hits to the fence.
Sarfraz narrowly missed his fourth Test century when he ambitiously attempted to sweep a ball from seamer Dhammika Prasad that was pitched outside the off-stump and dragged the ball onto his stumps.
Sarfraz and Shafiq had joined hands on Friday evening after the fall of skipper Misbah-ul Haq's wicket had threatened a total collapse.
When Sarfraz reached 47, he had completed 1,000 Test runs in 28 innings to equal Imtiaz Ahmed's record of being the fastest to the mark among Pakistan's wicket-keepers.
When Pakistan resumed after lunch at 259-6, Shafiq was supported by Wahab Riaz (14) and Yasir Shah (23) before Babar joined hands in an entertaining partnership.
Bad weather had washed out the entire first day's play on Wednesday and just 64 overs were bowled on the second day due to a wet outfield.
