Often, during my work, I must check for the user that is launching my applications, specifically some applications like ping/shutdown/../.. need to be executed by root user.

I collected four pieces of code in four languages 

 

Ruby

raise 'Must run as root' unless Process.uid == 0

 

C

if(getuid()!=0)

{

    printf("You must be root to run this app\n");

    exit(EXIT_FAILURE);

}

 

bash 

if [ "$(id -u)" != "0" ]; then

   echo "This script must be run as root" 1>&2

   exit 1

fi

 

perl

$login = (getpwuid($>)); if (!$login == "root") { die "\nYou cannot run this Perl script as user \"$login\", must be ROOT!\n\n"; }

As suggested by Renée there was a bug so use the following:

my $login = (getpwuid $>);
die "must run as root" if $login ne 'root';

Gg1