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.
Header¶
Prototype¶
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
EPIPEwhen the peer has closed a pipe or socket.