Skip to content

write()

Purpose

write() writes bytes from a userspace buffer to a file descriptor.

It is used for device nodes, pipes, sockets, sysfs files, eventfd notifications, and regular files.

#include <unistd.h>

Prototype

ssize_t write(int fd, const void *buf, size_t count);

Parameters

Parameter Description
fd File descriptor to write to.
buf Source buffer.
count Number of bytes to write.

Return Value

Returns the number of bytes written. Returns -1 on failure and sets errno.

Minimal Example

const char cmd[] = "start
";
ssize_t n = write(fd, cmd, sizeof(cmd) - 1);
if (n < 0) {
    perror("write");
    return -1;
}

Common Pitfalls

  • Assuming a single write() always writes the entire buffer.
  • Not handling partial writes on sockets or non-blocking fds.
  • Writing invalid command strings to sysfs-style control files.
  • Ignoring EPIPE when the peer has closed a pipe or socket.