Recording via System Calls C# Mono Linux
Trying to write an integer value to the Linux system address
/sys/class/backlight/backlight/brightness
I use Mono Posix. I'm doing something wrong, because the error Invalid argument [EINVAL] pops up. Perhaps I am not writing the value correctly.
Connecting dynamic libraries:
[DllImport("libc.so.6", EntryPoint = "open")]
public static extern int Open(string fileName, int mode);
[DllImport("libc.so.6", EntryPoint = "fcntl", SetLastError = true)]
private static extern int Fcntl(int fd, int request, int data);
private const string Path = "/sys/class/backlight/backlight/brightness";
private int fd = -1;
Next, I open the "file":
private void Open()
{
fd = Syscall.open(Path, OpenFlags.O_RDWR);
if (fd < 0)
{
CheckAndThrowUnixIOException();
}
}
And I try to write it down:
public unsafe void WriteValue(int value)
{
Open();
var ret = Fcntl(fd, 1, value); // что - то тут не так
int count;
var data = new char[1];
data[0] = (char) value; // и тут тоже что-то не правильно? Нужно значение в IntPtr.
fixed(char* p = data)
{
count = (int)Syscall.write(fd, p, (ulong) data.Length);
}
if (count < 0)
{
CheckAndThrowUnixIOException(); // Соответственно тут летит ошибка.
}
}
Sampling method exceptions:
private void CheckAndThrowUnixIOException()
{
var error = Marshal.GetLastWin32Error();
throw new UnixIOException(error);
}
I can't figure out how to write the value to sys/class.... It is also not clear how one can read the address from the Path constant.
0
1 answers
I figured out, it was necessary to pass a string literal as a pointer:
[DllImport("libc.so.6", EntryPoint = "open")]
public static extern int Open(string fileName, int mode);
private void Open()
{
fileDescriptor = Syscall.open(BrightnessPath, OpenFlags.O_RDWR);
if (fileDescriptor < 0) CheckAndThrowUnixIOException();
}
private void OpenIfNotOpen()
{
if (!IsOpen) Open();
}
public unsafe void WriteBrightnessValue(int value)
{
if (value <= MaxBrightness)
{
var buffer = value.Map(value);
var str = buffer.ToString();
OpenIfNotOpen();
int fdValue;
fixed (char* ptStr = str)
{
fdValue = (int) Syscall.write(fileDescriptor, ptStr, (ulong) str.Length);
}
if (fdValue < 0)
{
CheckAndThrowUnixIOException();
}
Close();
Logger.Debug("-- File descriptor has been closed");
}
}
1
Author: JDo, 2019-09-24 12:02:59