Feature or bug?

Using shell echo to write to /sys files normally adds an implicit
newline but
write() in a C program must add it explicitly. Some but not all /sys files
require a newline or the write fails. 'Extra' new lines from echo are
silently ignored and do not cause errors.

For example:
writing "1" to /sys/block/sd*/device/delete does not require a trailing
newline
writing "offline" to  /sys/block/sd*/device/state does require a
trailing newline

$ make test
$ sudo ./test
write failed without newline: Invalid argument

===================================================
// Test program to illustrate required newline for writes to
/sys/block/sd*/device/state
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
    int sysfd;
    
    if ((sysfd = open("/sys/block/sdb/device/state", O_WRONLY)) < 0)
        perror("open failed");
    else
    {
        if (write(sysfd, "offline", 7) < 0)
            perror("write failed without newline");
        if (write(sysfd, "offline\n", 8) < 0)
            perror("write failed with newline");
        if (close(sysfd))
            perror("close failed");
    }

    return 0;
}

Reply via email to