Writing to configfs sysfs from C++ fails but works if done with bash commands

276 Views Asked by At

An small update: I was able to write to my sysfs path with freopen :)

Trying to play around with my phone's usb gadget, and enable myself to use my phone to serve an ISO to my PC, I've noticed something very weird.

With the code bellow, I'm trying to write the usb controller name to /sys/kernel/config/usb_gadget/g1/UDC but I always run into Device or resource busy while doing echo from the cmdline works perfectly fine. Any way to fix this without using system() ?

void sysfs_write(char *path, char *content)
{
    std::cout << "Write: " << content << " -> " << path << std::endl;
    int fd = open(path, O_WRONLY);
    if (fd == -1)
    {
        perror("Failed");
        return;
    }
    int n = write(fd, content, strlen(content));
    if (n == -1)
    {
        perror("Failed");
    }
    close(fd);
}


sysfs_write("/sys/kernel/config/usb_gadget/g1/UDC", "");
sysfs_write("/sys/kernel/config/usb_gadget/g1/UDC" , "a600000.dwc3");
// Both fail with Device or resource busy
  • stat
  File: /sys/kernel/config/usb_gadget/g1/UDC
  Size: 4096        Blocks: 0          IO Block: 4096   regular file
Device: 0,17    Inode: 249229      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-02-01 01:17:16.229999999 +0200
Modify: 2023-02-01 01:28:46.424746782 +0200
Change: 2023-02-01 01:28:46.424746782 +0200
 Birth: -
  File: /sys/kernel/config/usb_gadget/g1
  Size: 0           Blocks: 0          IO Block: 4096   directory
Device: 0,17    Inode: 18684       Links: 4
Access: (0755/drwxr-xr-x)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2023-02-01 01:18:00.646458114 +0200
Modify: 2023-02-01 01:17:23.679999997 +0200
Change: 2023-02-01 01:17:23.679999997 +0200
 Birth: -
1

There are 1 best solutions below

0
Alexandru Nitan On

Ok, so RIP me. I had it from the first try, but my code was broken somewhere else, since I'm building the path I'm giving to the function, and after I fixed that I just assumed I already tried this but I guess not.

void sysfs_write(char *path, char *content)
{
    std::cout << "Write: " << content << " -> " << path << std::endl;
    std::ofstream sysfsFile(path);
    sysfsFile << content << std::endl;
    sysfsFile.close();
}