Skip to content

ftruncate()

Purpose

Sets the size of a file or POSIX shared memory object.

#include <unistd.h>

Prototype

int ftruncate(int fd, off_t length);

Parameters

  • fd: open file descriptor.
  • length: target size in bytes.

Return Value

  • Success: returns 0.
  • Failure: returns -1 and sets errno.

Minimal Example

int fd = shm_open("/demo_shm", O_CREAT | O_RDWR, 0600);
if (fd >= 0) {
    ftruncate(fd, sizeof(struct shared_data));
}

Common Pitfalls

  • POSIX shared memory objects have size 0 after creation.
  • Call ftruncate() before mmap() when creating the object.
  • Existing mappings are not automatically revalidated if the object is resized incorrectly.