Конспекты

os610.sh

Код · 870 строк · 26 КБ

#!/bin/bash
# Practicals 6-10: create sources in ~/practice6 ... ~/practice10
command -v gcc >/dev/null || echo "gcc не найден: после этого выполни sudo apt install -y gcc"
ipcrm -M 0x4F5306 2>/dev/null; ipcrm -S 0x4F5307 2>/dev/null; ipcrm -Q 0x4F5308 2>/dev/null
mkdir -p ~/practice6
cat > ~/practice6/writer.c <<'__END__'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_KEY 0x4F5306

int main() {
    // Размер своего исходника определяем через lseek
    int fd = open("writer.c", O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    off_t size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    // +1 байт под завершающий \0
    int shmid = shmget(SHM_KEY, size + 1, IPC_CREAT | 0666);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }
    char *mem = shmat(shmid, NULL, 0);
    if (mem == (void *)-1) {
        perror("shmat");
        return 1;
    }

    ssize_t n = read(fd, mem, size);
    if (n == -1) {
        perror("read");
        return 1;
    }
    mem[n] = '\0';
    close(fd);

    printf("Писатель: в сегмент %d записано %zd байт\n", shmid, n);
    shmdt(mem);
    return 0;
}
__END__
cat > ~/practice6/reader.c <<'__END__'
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_KEY 0x4F5306

int main() {
    int shmid = shmget(SHM_KEY, 0, 0666);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }

    // Размер сегмента берём из shmctl, чтобы знать, сколько печатать
    struct shmid_ds info;
    if (shmctl(shmid, IPC_STAT, &info) == -1) {
        perror("shmctl IPC_STAT");
        return 1;
    }

    char *mem = shmat(shmid, NULL, SHM_RDONLY);
    if (mem == (void *)-1) {
        perror("shmat");
        return 1;
    }

    write(STDOUT_FILENO, mem, info.shm_segsz - 1);
    printf("--- Читатель: прочитано %zu байт ---\n", (size_t)info.shm_segsz - 1);

    shmdt(mem);
    // Удаляем сегмент из системы
    if (shmctl(shmid, IPC_RMID, NULL) == -1) {
        perror("shmctl IPC_RMID");
        return 1;
    }
    return 0;
}
__END__
cat > ~/practice6/threads.c <<'__END__'
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 256

static int shmid;
static pthread_t writer_tid;

// Поток-писатель: создаёт сегмент и кладёт в него строку
static void *writer_thread(void *arg) {
    (void)arg;
    shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT | 0600);
    if (shmid == -1) {
        perror("shmget");
        return NULL;
    }
    char *mem = shmat(shmid, NULL, 0);
    if (mem == (void *)-1) {
        perror("shmat");
        return NULL;
    }
    strcpy(mem, "Сообщение из потока-писателя через разделяемую память");
    printf("Поток-писатель: записал строку в сегмент %d\n", shmid);
    shmdt(mem);
    return NULL;
}

// Поток-читатель: ждёт писателя, читает строку и удаляет сегмент
static void *reader_thread(void *arg) {
    (void)arg;
    pthread_join(writer_tid, NULL);
    char *mem = shmat(shmid, NULL, SHM_RDONLY);
    if (mem == (void *)-1) {
        perror("shmat");
        return NULL;
    }
    printf("Поток-читатель: прочитал \"%s\"\n", mem);
    shmdt(mem);
    shmctl(shmid, IPC_RMID, NULL);
    return NULL;
}

int main() {
    pthread_t reader_tid;
    pthread_create(&writer_tid, NULL, writer_thread, NULL);
    pthread_create(&reader_tid, NULL, reader_thread, NULL);
    pthread_join(reader_tid, NULL);
    return 0;
}
__END__
mkdir -p ~/practice7
cat > ~/practice7/writer.c <<'__END__'
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>

#define SHM_KEY 0x4F5306
#define SEM_KEY 0x4F5307

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
};

static void semaphore_wait(int semid) {
    struct sembuf op = {0, -1, 0};
    if (semop(semid, &op, 1) == -1) {
        perror("semop wait");
        exit(1);
    }
}

static void semaphore_signal(int semid) {
    struct sembuf op = {0, 1, 0};
    if (semop(semid, &op, 1) == -1) {
        perror("semop signal");
        exit(1);
    }
}

// Необязательный аргумент - пауза в секундах в критической секции (для демо)
int main(int argc, char *argv[]) {
    int delay = argc > 1 ? atoi(argv[1]) : 0;

    int fd = open("writer.c", O_RDONLY);
    if (fd == -1) {
        perror("open");
        return 1;
    }
    off_t size = lseek(fd, 0, SEEK_END);
    lseek(fd, 0, SEEK_SET);

    int shmid = shmget(SHM_KEY, size + 1, IPC_CREAT | 0666);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }
    char *mem = shmat(shmid, NULL, 0);
    if (mem == (void *)-1) {
        perror("shmat");
        return 1;
    }

    // Семафор создаётся здесь и получает начальное значение 1
    int semid = semget(SEM_KEY, 1, IPC_CREAT | 0666);
    if (semid == -1) {
        perror("semget");
        return 1;
    }
    union semun arg;
    arg.val = 1;
    if (semctl(semid, 0, SETVAL, arg) == -1) {
        perror("semctl SETVAL");
        return 1;
    }

    semaphore_wait(semid);
    printf("Писатель: семафор захвачен, пишу в память\n");
    fflush(stdout);
    sleep(delay);
    ssize_t n = read(fd, mem, size);
    if (n == -1) {
        perror("read");
        return 1;
    }
    mem[n] = '\0';
    close(fd);
    printf("Писатель: записано %zd байт, семафор освобождён\n", n);
    semaphore_signal(semid);

    shmdt(mem);
    return 0;
}
__END__
cat > ~/practice7/reader.c <<'__END__'
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>

#define SHM_KEY 0x4F5306
#define SEM_KEY 0x4F5307

static void semaphore_wait(int semid) {
    struct sembuf op = {0, -1, 0};
    if (semop(semid, &op, 1) == -1) {
        perror("semop wait");
        exit(1);
    }
}

static void semaphore_signal(int semid) {
    struct sembuf op = {0, 1, 0};
    if (semop(semid, &op, 1) == -1) {
        perror("semop signal");
        exit(1);
    }
}

int main() {
    int shmid = shmget(SHM_KEY, 0, 0666);
    if (shmid == -1) {
        perror("shmget");
        return 1;
    }
    int semid = semget(SEM_KEY, 1, 0666);
    if (semid == -1) {
        perror("semget");
        return 1;
    }

    struct shmid_ds info;
    if (shmctl(shmid, IPC_STAT, &info) == -1) {
        perror("shmctl IPC_STAT");
        return 1;
    }
    char *mem = shmat(shmid, NULL, SHM_RDONLY);
    if (mem == (void *)-1) {
        perror("shmat");
        return 1;
    }

    printf("Читатель: жду семафор\n");
    fflush(stdout);
    semaphore_wait(semid);
    write(STDOUT_FILENO, mem, info.shm_segsz - 1);
    printf("--- Читатель: прочитано %zu байт ---\n", (size_t)info.shm_segsz - 1);
    semaphore_signal(semid);

    shmdt(mem);
    shmctl(shmid, IPC_RMID, NULL);
    semctl(semid, 0, IPC_RMID);
    return 0;
}
__END__
mkdir -p ~/practice8
cat > ~/practice8/common.h <<'__END__'
#ifndef COMMON_H
#define COMMON_H

#include <sys/types.h>

#define QUEUE_KEY 0x4F5308

// Типы сообщений. Чем меньше тип, тем выше приоритет у сервера.
#define TYPE_KILL 1      // сообщение от киллера
#define TYPE_REQUEST 2   // запрос клиента
// Ответ клиенту получает тип, равный его PID (PID всегда больше 2),
// поэтому сервер с порогом TYPE_REQUEST ответы не видит.

struct message {
    long mtype;
    pid_t pid;
    float value;
};

#define MSG_SIZE (sizeof(struct message) - sizeof(long))

#endif
__END__
cat > ~/practice8/server.c <<'__END__'
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "common.h"

static int qid = -1;

static void cleanup(void) {
    if (qid != -1) {
        msgctl(qid, IPC_RMID, NULL);
        qid = -1;
    }
}

static void on_signal(int sig) {
    (void)sig;
    cleanup();
    _exit(0);
}

int main() {
    // IPC_EXCL: если очередь уже есть, значит сервер запущен
    qid = msgget(QUEUE_KEY, IPC_CREAT | IPC_EXCL | 0666);
    if (qid == -1) {
        if (errno == EEXIST)
            fprintf(stderr, "Сервер уже запущен, второй экземпляр не нужен\n");
        else
            perror("msgget");
        return 1;
    }
    atexit(cleanup);
    signal(SIGINT, on_signal);
    signal(SIGTERM, on_signal);

    printf("Сервер запущен, очередь %d\n", qid);
    fflush(stdout);

    struct message msg;
    for (;;) {
        // Отрицательный msgtyp: берём наименьший тип, но не больше TYPE_REQUEST
        if (msgrcv(qid, &msg, MSG_SIZE, -TYPE_REQUEST, 0) == -1) {
            if (errno == EINTR)
                continue;
            perror("msgrcv");
            return 1;
        }
        if (msg.mtype == TYPE_KILL) {
            printf("Сервер: получен сигнал от киллера, завершаюсь\n");
            fflush(stdout);
            break;
        }
        printf("Сервер: от клиента %d получено %g\n", (int)msg.pid, msg.value);
        fflush(stdout);
        struct message reply = {msg.pid, getpid(), msg.value * msg.value};
        if (msgsnd(qid, &reply, MSG_SIZE, 0) == -1)
            perror("msgsnd");
    }
    // cleanup() удалит очередь, и новый сервер сможет стартовать сразу
    return 0;
}
__END__
cat > ~/practice8/client.c <<'__END__'
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "common.h"

int main() {
    int qid = msgget(QUEUE_KEY, 0666);
    if (qid == -1) {
        perror("msgget (сервер не запущен?)");
        return 1;
    }

    // подсказка только при вводе с клавиатуры
    int tty = isatty(STDIN_FILENO);
    float x;
    if (tty) {
        printf("Введите число: ");
        fflush(stdout);
    }
    while (scanf("%f", &x) == 1) {
        struct message req = {TYPE_REQUEST, getpid(), x};
        if (msgsnd(qid, &req, MSG_SIZE, 0) == -1) {
            perror("msgsnd");
            return 1;
        }
        struct message ans;
        // Ответ предназначен только нам: тип сообщения равен нашему PID
        if (msgrcv(qid, &ans, MSG_SIZE, getpid(), 0) == -1) {
            perror("msgrcv");
            return 1;
        }
        printf("Ответ сервера: %g\n", ans.value);
        if (tty) {
            printf("Введите число: ");
            fflush(stdout);
        }
    }
    if (tty)
        printf("\n");
    return 0;
}
__END__
cat > ~/practice8/killer.c <<'__END__'
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include "common.h"

int main() {
    int qid = msgget(QUEUE_KEY, 0666);
    if (qid == -1) {
        perror("msgget (сервер не запущен?)");
        return 1;
    }
    struct message msg = {TYPE_KILL, getpid(), 0};
    if (msgsnd(qid, &msg, MSG_SIZE, 0) == -1) {
        perror("msgsnd");
        return 1;
    }
    printf("Киллер: сообщение отправлено\n");
    return 0;
}
__END__
mkdir -p ~/practice9
cat > ~/practice9/prodcons.c <<'__END__'
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

#define BUF_SIZE 10
#define ITEMS 30
#define CONSUMERS 3

static int buffer[BUF_SIZE];
static int head = 0;    // откуда читаем
static int tail = 0;    // куда пишем
static int count = 0;   // сколько элементов лежит в буфере
static int done = 0;    // производитель закончил

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
static pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;

static long consumed_sum[CONSUMERS];
static int consumed_cnt[CONSUMERS];

static void *producer(void *arg) {
    (void)arg;
    for (int i = 1; i <= ITEMS; i++) {
        pthread_mutex_lock(&mutex);
        while (count == BUF_SIZE) {
            printf("Производитель: буфер полон, жду\n");
            pthread_cond_wait(&not_full, &mutex);
        }
        buffer[tail] = i;
        tail = (tail + 1) % BUF_SIZE;
        count++;
        printf("Производитель: положил %d (в буфере %d)\n", i, count);
        pthread_cond_signal(&not_empty);
        pthread_mutex_unlock(&mutex);
    }
    // Сообщаем, что элементов больше не будет, и будим всех потребителей
    pthread_mutex_lock(&mutex);
    done = 1;
    pthread_cond_broadcast(&not_empty);
    pthread_mutex_unlock(&mutex);
    return NULL;
}

static void *consumer(void *arg) {
    int id = (int)(long)arg;
    for (;;) {
        pthread_mutex_lock(&mutex);
        while (count == 0 && !done)
            pthread_cond_wait(&not_empty, &mutex);
        if (count == 0 && done) {
            pthread_mutex_unlock(&mutex);
            break;
        }
        int item = buffer[head];
        head = (head + 1) % BUF_SIZE;
        count--;
        printf("  Потребитель %d: взял %d (в буфере %d)\n", id, item, count);
        pthread_cond_signal(&not_full);
        pthread_mutex_unlock(&mutex);

        consumed_sum[id - 1] += item;
        consumed_cnt[id - 1]++;
        usleep(20000 * id);   // имитация обработки, потребители разной скорости
    }
    return NULL;
}

int main() {
    pthread_t prod, cons[CONSUMERS];

    pthread_create(&prod, NULL, producer, NULL);
    for (long i = 1; i <= CONSUMERS; i++)
        pthread_create(&cons[i - 1], NULL, consumer, (void *)i);

    pthread_join(prod, NULL);
    for (int i = 0; i < CONSUMERS; i++)
        pthread_join(cons[i], NULL);

    long total = 0;
    int taken = 0;
    for (int i = 0; i < CONSUMERS; i++) {
        printf("Потребитель %d обработал %d элементов\n", i + 1, consumed_cnt[i]);
        total += consumed_sum[i];
        taken += consumed_cnt[i];
    }
    printf("Всего обработано %d из %d, сумма %ld (ожидалась %d)\n",
           taken, ITEMS, total, ITEMS * (ITEMS + 1) / 2);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&not_full);
    pthread_cond_destroy(&not_empty);
    return 0;
}
__END__
mkdir -p ~/practice10
cat > ~/practice10/symlink_depth.c <<'__END__'
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>

int main() {
    // Всё создаём в отдельной директории, чтобы потом удалить одной командой
    if (mkdir("symlink_test", 0755) == -1) {
        perror("mkdir symlink_test");
        return 1;
    }
    if (chdir("symlink_test") == -1) {
        perror("chdir");
        return 1;
    }

    int fd = creat("a", 0644);
    if (fd == -1) {
        perror("creat");
        return 1;
    }
    close(fd);

    char prev[64] = "a";
    char name[64];
    int depth = 0;

    for (;;) {
        snprintf(name, sizeof(name), "link%d", depth + 1);
        if (symlink(prev, name) == -1) {
            perror("symlink");
            return 1;
        }
        fd = open(name, O_RDONLY);
        if (fd == -1) {
            if (errno == ELOOP) {
                printf("Файл %s открыть не удалось: %s\n", name, strerror(errno));
                break;
            }
            perror("open");
            return 1;
        }
        close(fd);
        depth++;
        strcpy(prev, name);
    }

    printf("Глубина рекурсии: %d символьных связей\n", depth);
    return 0;
}
__END__
cat > ~/practice10/myls.c <<'__END__'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <sys/stat.h>

static const char *file_type(mode_t m) {
    if (S_ISREG(m)) return "обычный файл";
    if (S_ISDIR(m)) return "каталог";
    if (S_ISLNK(m)) return "символьная ссылка";
    if (S_ISCHR(m)) return "символьное устройство";
    if (S_ISBLK(m)) return "блочное устройство";
    if (S_ISFIFO(m)) return "FIFO";
    if (S_ISSOCK(m)) return "сокет";
    return "неизвестно";
}

static int by_name(const struct dirent **a, const struct dirent **b) {
    return strcmp((*a)->d_name, (*b)->d_name);
}

int main(int argc, char *argv[]) {
    const char *dir = argc > 1 ? argv[1] : ".";

    struct dirent **list;
    int n = scandir(dir, &list, NULL, by_name);
    if (n == -1) {
        perror(dir);
        return 1;
    }

    for (int i = 0; i < n; i++) {
        char path[PATH_MAX];
        snprintf(path, sizeof(path), "%s/%s", dir, list[i]->d_name);

        struct stat st;
        if (lstat(path, &st) == -1) {
            perror(path);
            continue;
        }
        printf("%-20s %s", list[i]->d_name, file_type(st.st_mode));
        if (S_ISLNK(st.st_mode)) {
            char target[PATH_MAX];
            ssize_t len = readlink(path, target, sizeof(target) - 1);
            if (len != -1) {
                target[len] = '\0';
                printf(" -> %s", target);
            }
        }
        printf("\n");
        free(list[i]);
    }
    free(list);
    return 0;
}
__END__
cat > ~/practice10/myls_al.c <<'__END__'
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dirent.h>
#include <unistd.h>
#include <limits.h>
#include <pwd.h>
#include <grp.h>
#include <sys/stat.h>
#include <sys/sysmacros.h>
#include <sys/xattr.h>

struct entry {
    char name[NAME_MAX + 1];
    struct stat st;
    char target[PATH_MAX];
    int is_link;
    int has_acl;
};

static int cmp(const void *a, const void *b) {
    const struct entry *x = a, *y = b;
    return strcmp(x->name, y->name);
}

static void mode_string(mode_t m, char *s) {
    if (S_ISREG(m)) s[0] = '-';
    else if (S_ISDIR(m)) s[0] = 'd';
    else if (S_ISLNK(m)) s[0] = 'l';
    else if (S_ISCHR(m)) s[0] = 'c';
    else if (S_ISBLK(m)) s[0] = 'b';
    else if (S_ISFIFO(m)) s[0] = 'p';
    else if (S_ISSOCK(m)) s[0] = 's';
    else s[0] = '?';
    const char *rwx = "rwxrwxrwx";
    for (int i = 0; i < 9; i++)
        s[i + 1] = (m & (1 << (8 - i))) ? rwx[i] : '-';
    if (m & S_ISUID) s[3] = (m & S_IXUSR) ? 's' : 'S';
    if (m & S_ISGID) s[6] = (m & S_IXGRP) ? 's' : 'S';
    if (m & S_ISVTX) s[9] = (m & S_IXOTH) ? 't' : 'T';
    s[10] = '\0';
}

static int num_width(unsigned long v) {
    int w = 1;
    while (v >= 10) { v /= 10; w++; }
    return w;
}

int main(int argc, char *argv[]) {
    const char *dir = argc > 1 ? argv[1] : ".";
    DIR *d = opendir(dir);
    if (!d) {
        perror(dir);
        return 1;
    }

    struct entry *e = NULL;
    int n = 0, cap = 0;
    struct dirent *de;
    while ((de = readdir(d)) != NULL) {
        if (n == cap) {
            cap = cap ? cap * 2 : 64;
            e = realloc(e, cap * sizeof(*e));
            if (!e) {
                perror("realloc");
                return 1;
            }
        }
        struct entry *x = &e[n];
        strcpy(x->name, de->d_name);
        char path[PATH_MAX];
        snprintf(path, sizeof(path), "%s/%s", dir, de->d_name);
        if (lstat(path, &x->st) == -1) {
            perror(path);
            continue;
        }
        x->is_link = S_ISLNK(x->st.st_mode);
        // как в ls Ubuntu: "+" после прав, если у файла есть расширенные атрибуты
        // (ACL, capabilities); у символьной ссылки смотрится файл, на который она указывает
        char names[1024];
        ssize_t nx = listxattr(path, names, sizeof(names));
        x->has_acl = nx > 0 || (nx == -1 && errno == ERANGE);
        if (x->is_link) {
            ssize_t len = readlink(path, x->target, sizeof(x->target) - 1);
            x->target[len > 0 ? len : 0] = '\0';
        }
        n++;
    }
    closedir(d);
    qsort(e, n, sizeof(*e), cmp);

    // Первый проход: ширины колонок и "total" (в блоках по 1 КиБ)
    long long total = 0;
    int any_acl = 0;
    int w_link = 1, w_user = 0, w_group = 0, w_size = 1, w_major = 0, w_minor = 0, w_dev = 0;
    for (int i = 0; i < n; i++) {
        struct stat *st = &e[i].st;
        total += st->st_blocks;
        if (e[i].has_acl) any_acl = 1;
        if (num_width(st->st_nlink) > w_link) w_link = num_width(st->st_nlink);
        struct passwd *pw = getpwuid(st->st_uid);
        int lu = pw ? (int)strlen(pw->pw_name) : num_width(st->st_uid);
        struct group *gr = getgrgid(st->st_gid);
        int lg = gr ? (int)strlen(gr->gr_name) : num_width(st->st_gid);
        if (lu > w_user) w_user = lu;
        if (lg > w_group) w_group = lg;
        if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)) {
            int wa = num_width(major(st->st_rdev));
            int wb = num_width(minor(st->st_rdev));
            if (wa > w_major) w_major = wa;
            if (wb > w_minor) w_minor = wb;
            if (wa + 2 + wb > w_dev) w_dev = wa + 2 + wb;
        } else if (num_width(st->st_size) > w_size) {
            w_size = num_width(st->st_size);
        }
    }
    // ширина колонки размера: самое длинное число или самая длинная пара "major, minor"
    if (w_dev > w_size)
        w_size = w_dev;
    printf("total %lld\n", total / 2);

    time_t now = time(NULL);
    for (int i = 0; i < n; i++) {
        struct stat *st = &e[i].st;
        char mode[11];
        mode_string(st->st_mode, mode);

        struct passwd *pw = getpwuid(st->st_uid);
        struct group *gr = getgrgid(st->st_gid);
        char user[32], group[32];
        if (pw) snprintf(user, sizeof(user), "%s", pw->pw_name);
        else snprintf(user, sizeof(user), "%u", st->st_uid);
        if (gr) snprintf(group, sizeof(group), "%s", gr->gr_name);
        else snprintf(group, sizeof(group), "%u", st->st_gid);

        char tbuf[32];
        struct tm tm;
        localtime_r(&st->st_mtime, &tm);
        // как в ls: файлы старше полугода показываются с годом вместо времени
        if (st->st_mtime > now || now - st->st_mtime > 15778476)
            strftime(tbuf, sizeof(tbuf), "%b %e  %Y", &tm);
        else
            strftime(tbuf, sizeof(tbuf), "%b %e %H:%M", &tm);

        // если хотя бы у одного файла есть ACL, ls добавляет колонку под "+" у всех строк
        const char *acl = any_acl ? (e[i].has_acl ? "+" : " ") : "";
        printf("%s%s %*lu %-*s %-*s ", mode, acl, w_link, (unsigned long)st->st_nlink,
               w_user, user, w_group, group);
        if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
            printf("%*u, %*u", w_size - w_minor - 2 > w_major ? w_size - w_minor - 2 : w_major,
                   major(st->st_rdev),
                   w_minor, minor(st->st_rdev));
        else
            printf("%*lld", w_size, (long long)st->st_size);
        printf(" %s %s", tbuf, e[i].name);
        if (e[i].is_link)
            printf(" -> %s", e[i].target);
        printf("\n");
    }
    free(e);
    return 0;
}
__END__
cat > ~/practice10/README <<'__END__'
myls_al - упрощённый аналог команды ls -al

Сборка:
    gcc -Wall -Wextra -o myls_al myls_al.c

Запуск:
    ./myls_al [каталог]
Без аргумента выводится содержимое текущего каталога.

Что выводится (как в ls -al): строка "total", затем для каждой записи,
включая . и .., в порядке сортировки по имени:
    тип и права (-rwxr-xr-x, d, l, c, b, p, s; биты s/S и t/T),
    число жёстких ссылок, владелец, группа,
    размер в байтах (для устройств - старший и младший номера через запятую),
    время изменения (файлы старше полугода - с годом вместо времени),
    имя; для символьных ссылок после " -> " цель ссылки.
Если у файла есть расширенные атрибуты (ACL, capabilities), после прав
ставится "+", а у остальных строк в этом каталоге пробел (как делает ls
в Ubuntu). Ширина колонки размера считается по самому длинному числу
или самой длинной паре "major, minor" у устройств.

Отличия от настоящего ls -al:
    сортировка по strcmp, без учёта локали;
    нет значка "." (контекст SELinux) после прав;
    нет цветов и кавычек вокруг имён с пробелами;
    параметры командной строки не разбираются, принимается только один каталог.

Для сравнения: LC_ALL=C ls -al /dev  и  ./myls_al /dev
(LC_ALL=C нужен, чтобы ls печатал даты по-английски)

Остальные файлы:
    symlink_depth.c - глубина рекурсии символьных связей (каталог symlink_test);
    myls.c          - аналог ls: имена, типы, цели ссылок.
__END__
rm -rf ~/practice10/symlink_test
echo "Готово: файлы лежат в ~/practice6 ... ~/practice10"