stylistic:style_transfer, information:classification
Later life

Ibn Khaldun said of Egypt, "He who has not seen it does not know the power of Islam." While other Islamic regions had to cope with border wars and inner strife, Mamluk Egypt enjoyed prosperity and high culture. In 1384, the Egyptian Sultan, al-Malik udh-Dhahir Barquq, made Khaldun professor of the Qamhiyyah Madrasah and appointed him as the Grand qadi of the Maliki school of fiqh (one of four schools, the Maliki school was widespread primarily in Western Africa). His efforts at reform encountered resistance, however, and within a year, he had to resign his judgeship. Also in 1384, a ship carrying Khaldun's wife and children sank off of Alexandria.

After his return from a pilgrimage to Mecca in May 1388, Ibn Khaldūn concentrated on teaching at various Cairo madrasas. At the Mamluk court he fell from favor because during revolts against Barquq, he had, apparently under duress, with other Cairo jurists, issued a fatwa against Barquq. Later relations with Barquq returned to normal, and he was once again named the Maliki qadi. Altogether, he was called six times to that high office, which, for various reasons, he never held long.

In 1401, under Barquq's successor, his son Faraj, Ibn Khaldūn took part in a military campaign against the Mongol conqueror, Timur, who besieged Damascus in 1400. Ibn Khaldūn cast doubt upon the viability of the venture and really wanted to stay in Egypt. His doubts were vindicated, as the young and inexperienced Faraj, concerned about a revolt in Egypt, left his army to its own devices in Syria and hurried home. Ibn Khaldūn remained at the besieged city for seven weeks, being lowered over the city wall by ropes to negotiate with Timur, in a historic series of meetings that he reported extensively in his autobiography. Timur questioned him in detail about conditions in the lands of the Maghreb. At his request, Ibn Khaldūn even wrote a long report about it. As he recognized Timur's intentions, he did not hesitate, on his return to Egypt, to compose an equally-extensive report on the history of the Tatars, together with a character study of Timur, sending them to the Merinid rulers in Fez.

Ibn Khaldūn spent the next five years in Cairo completing his autobiography and his history of the world and acting as teacher and judge. Meanwhile, he was alleged to have joined an underground party, Rijal Hawa Rijal, whose reform -oriented ideals attracted the attention of local political authorities. The elderly Ibn Khaldun was placed under arrest. He died on 17 March 1406, one month after his sixth selection for the office of the Maliki qadi (Judge).