简体   繁体   中英

How do I make my user level application communicate to a root level application through pipes?

I have a user level application that needs to enable/disable a device by writing to it's device file(which requires root privileges).

Here's the current implementation of my interface:

bool DeviceInterface::EnableDevice( bool isEnabled )
{
    bool isSuccessful = false;

    //enable device
    if(isEnabled)
    {
        isSuccessful = (system("enableDevice.sh 1") == 0)? true : false;
    }
    //disable device
    else
    {
        isSuccessful = (system("enableDevice.sh 0") == 0)? true : false;
    }
    return isSuccessful ;
}

My script "enableDevice.sh" simply looks like this, and runs just fine when ran as root:

echo $1 > /sys/devices/device_file

This fails as it requires root privileges to be able to write to a device file. I'm totally new to "pipes", "fork" and "exec". Can anybody help me how I could pass "0" or "1" to a script to enable and disable the device?

Run chmod on enableDevice.sh as follows ( being root) :-

   #chmod 4755 enableDevice.sh

It's called setting the setuid bit. With this non-root users will be able to run this script and it will run with the owner's ( who in our case : root) privileges. And thus your program will work. Do read about setuid. EDIT : Also, before chmod, make the owner and group of enableDevice.sh as root. Then only it will work.

In order for 'enableDevice.sh' to do this, it needs to be running as root. You could mark it suid (chmod u+S enableDevice.sh) and chown it to root. Note that you'll need to be root to do the chown (on any reasonable unix system).

Of course you could always open up write permissions for your (well, the programs') group or for everyone, ie chmod g+w,o+w /sys/devices/device_file

I REALLY wouldn't recommend you do this. if I called that script with '\\"bunch of nothing at all > /dev/sda' it'd overwrite the (likely) root of your system drive.

A better idea would be to have the script check what "$1" is, and then echo 0 or 1 to the device, or do nothing if it's neither. ie don't trust user data, especially in suid scripts!

case "$1" in
    enable)   VALUE=1 ;;
    disable)  VALUE=0 ;;
    *)        exit  ;;
esac
echo $VALUE > /sys/devices/device_file

Better still, have a deamon which you've run as root hanging around watching a named pipe which does (effectively) the above, depending on what it gets in the pipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM