'Raspberry Pi GPIO automatically resets to 0 using linux ioctl's

I have a relay connected to GPIO26 driven by a transistor on a Raspberry Pi 4. When the logical pin is set to 0, the relay is normally closed (delivering current to a led). However, in many of my projects I used to set 1 or 0 to simply turn on and off the led. However, with that relay normally closed with a logical GPIO set to 0 it looks like every time I try to write 1 (this time to turn it off) as long as I close the descriptor the relay get back to its original state and the led turn on again.

My question is: how can I keep the logical value without having the file descriptor open during the application lifetime?

This is my usual code:

int
gpio_write(int devfd, unsigned int pin, int value)
{
    struct gpio_v2_line_request req = {
        .offsets[0] = pin,
        .config.flags = GPIO_V2_LINE_FLAG_OUTPUT,
        .num_lines = 1
    };
    struct gpio_v2_line_values val = {
        .bits = value,
        .mask = 1
    };

    if (ioctl(devfd, GPIO_V2_GET_LINE_IOCTL, &req) < 0)
        return -1;
    if (ioctl(req.fd, GPIO_V2_LINE_SET_VALUES_IOCTL, &val) < 0) {
        close(req.fd);
        return -1;
    }

    // <- HERE the value stays to what I've set (either 0 or 1).

    close(req.fd);

    // <- HERE the relay gets back to its original state (mandatory 0).
    // And for some reason, it also reverts to input.

    return 0;
}

I don't have anything fancy in my /boot/config.txt regarding GPIOs configuration.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source