Longer distance trains have 2 engineers, and a toilet. So when you have to go, you just let the other person operate. Or on other lines, they may just stop the train, and go use a bathroom when needed. I'll answer this from a U.K. perspective, as that's where I live & work on the railway.