unistd.h
- C course
- Advanced
- Lesson 2/83
- 5 min
Learn basic functions in unistd.h.
The unistd.h header
unistd.h is the core POSIX header. It declares functions for file descriptors, processes and low-level I/O. The most common ones are read, write, close, fork and getpid.
These differ from fread/fwrite in stdio.h: they do not buffer, they work directly with descriptors. Each call returns ssize_t, the number of bytes read or written. On error it returns -1.
ssize_t and errno
POSIX I/O functions return a value of type ssize_t. This is a signed integer: positive on success, 0 at end of file, -1 on error.
On error the global errno variable is set. You include <errno.h> to read it. For example, when read fails, errno may be EAGAIN or EBADF. Always check the return value; if -1, inspect errno.
Practice Output with write
Define a message with const char *msg = "Merhaba\n";. Write it to stdout with write(1, msg, 8). The 8 is the byte count (Merhaba plus newline).
Starter code
#include <stdio.h>
#include <unistd.h>
// Define msg
// Write to stdout with write
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <unistd.h>
int main(void) {
const char *msg = "Merhaba\n";
write(1, msg, 8);
return 0;
}Expected output
Merhaba
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match functions to purposes
| Term | Meaning |
|---|---|
read |
Reads from file |
write |
Writes to file |
close |
Closes descriptor |
getpid |
Returns process ID |
2 In write(1, buf, n), what does 1 specify?
- The file name
- The file descriptor Correct answer
- The byte count
- The buffer size
Explanation: 1 is the stdout descriptor.
3 write call
ssize_t n = ____(1, msg, 8);
ssize_t n = write(1, msg, 8);
Explanation: write sends data to a descriptor.