Pi4J / pi4j-v2

Pi4J Version 2.0
Apache License 2.0
266 stars 54 forks source link

Context shutdown() does not appear to close files #285

Closed Rablet closed 1 year ago

Rablet commented 1 year ago

pi4j.shutdown() does not appear to close files. As an example, each time a pi4j context is initialised for an i2c provider the number of open /dev/i2c-X files opened increases by one. This causes an issue for long running programs which creates / shuts down pi4j contexts as part of its lifecycle.

Example code that demonstrates this with a BME280:

   private static void readSensor() {
        Context pi4j = Pi4J.newAutoContext();
        I2CProvider i2CProvider = pi4j.provider("linuxfs-i2c");
        I2CConfig i2cConfig = I2C.newConfigBuilder(pi4j).id("MySensor").bus(1).device(0x77).build();

        try (I2C sensorDev = i2CProvider.create(i2cConfig)) {
            // Read sensor here
        }
        pi4j.shutdown();
    }

    public static void main(String[] args) throws IOException {
        for (int i = 0; i < 10; i++) {
            readSensor();
        }
        try {
            TimeUnit.SECONDS.sleep(30);
            // At this point run sudo lsof -p <pidofjava> | grep /dev/i2c-1 | wc -l
            // there will be 10 opened - since they've all been closed I would expect zero
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Am I missing a step in order to make pi4j close /dev/i2c-1 when the context is closed?

eitch commented 1 year ago

Fixed in commit cc3b2bf2bb08a52ccdf1dce0c01d905ce8e8e39e

eitch commented 1 year ago

You may test the latest snapshot, which is currently being built, and should be ready in about 10 minutes.