This question has been asked here in multiple forms. I am asking it again because all these questions had too many details. Hence the answers all boiled down to how to solve those specific problems without jumping between users.
This I why am posting this as a new question (and immediately answering it below) for others that have this problem.
Suppose you have a perl script that you run as root where you first want to run things as root, then things as a regular user and then as root again.
For example:
#!/usr/bin/perl
#Problem 1: Make sure to start as root
system("whoami");
#Problem 2: Become your regular user
system("whoami");
#Problem 3: Become root again
system("whoami);
should be changed to show:
root
your_username
root
This the best solution I can think of.
If you want to start as root, become a regular user and become root again:
When starting as a regular user it's best to make sure that the parent stays a regular user and the child becomes root. You can do this like this: