I don’t know how it works in other countries but here in the Netherlands most professors write those textbooks during time they are already paid for by their employer, but pocket the revenue of the textbooks themselves. In the meanwhile they actively discourage the use of second-hand textbooks by requiring students to buy the latest edition each year.
For mathematics, all of my course materials were available in PDF format for free (which I could then print myself if I wished to). For Philosophy, the majority of readings were available through the library system. Some courses did require a textbook, but use of older editions was encouraged, and often a photocopied "pack" of the relevant chapters would be made available for a small fee (<£15) by the faculty office.
Source - I was in a class where a lecturer broke this rule. It was a £100 book with only two copies in the library for a class of 30-40. We (students) queried it and the lecturer was ordered to bring a printed copy (as in laser-printed) of the relevant chapters for each student.
In fact, in my experience the student union actually took advantage of that situation instead.
When I started studying at TU Delft in 1991 the student union had a deal with the local bookstore to give 10% discount to their members. So in your first week as a freshman you were told to become a member of the student union because you would get a discount on all those books written by professors.
The student union said they represented 95% of the students, but 90% of them were only a member of the union because of the discount.
Oh. I see they still have the discount, and the student union actually has their OWN (commercial) publishing house nowadays. https://www.delftacademicpress.nl/index_en.php
"Members of the VSSD get a considerable discount on the books of Delft Academic Press because the publishing company is part of the student union VSSD."
It does depend a bit on the university though. I've heard that some have a more oppositional relationship. And there are still issues with some students not feeling represented by the union. They are usually democratic institutions though, with every student getting a vote if they want it, which helps alleviate the worst of those issues.
With textbooks a reasonable amount of the money goes to the authors. Those professors write the textbooks and will lose out if you pirate them.
It is not so with papers though. The professors who write them lose little if anything when you pirate their research - those who lose money (elsevier and co) in that case are (rightly) perceived as not deserving anyway.