简体   繁体   中英

Linux daemon set /proc/

I once wrote a simple daemon in bash - also sets the values in /proc/*. For example,

echo 50 > /sys/class/backlight/acpi_video0/brightness

I want to rewrite in C + + and share - but how to use the /proc/* in C++? as the client

Remember: on Unix, everything is a file (well, granted, almost everything).

Your current shell code actually means: write the value 50 ( echo 50 ) into the file ( redirection operator > ) which name follows ( /sys/class/backlight/acpi_video0/brightness ).


In C++, just open /sys/class/backlight/acpi_video0/brightness as a file and read/write to it using whatever method you prefer: C++ fstream , C fopen/fread/fwrite , ...

Example with fstream (namely ofstream since we're only writing to it):

std::ofstream file("/sys/class/backlight/acpi_video0/brightness");
if (!file.is_open())
    throw std::runtime_error("Could not open the file");
file << 50;
file.close();

Code sample:

int val = 50;

FILE *f = fopen("/sys/class/backlight/acpi_video0/brightness", "w");
if (!f)
{
   fprintf(stderr, "Huh, couldn't open /sys/class ... ");
   exit(1);
}
fprintf(f, "%d", val);
fclose(f); 

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