From: Leonid Krivoshein <klark.devel@gmail.com>
To: make-initrd@lists.altlinux.org
Subject: Re: [make-initrd] [PATCH 1/3] Reimplement ueventd
Date: Mon, 15 May 2023 07:38:30 +0300
Message-ID: <ecf9f7a7-5f84-adaa-c374-1d02c8a7ff76@gmail.com> (raw)
In-Reply-To: <6b444ed922286eb3df8f5322b1bddf9c55753eb8.1683200226.git.gladkov.alexey@gmail.com>
On 5/4/23 16:42, Alexey Gladkov wrote:
> [...]
> diff --git a/datasrc/ueventd/queue-processor.c b/datasrc/ueventd/queue-processor.c
> new file mode 100644
> index 00000000..ab5e03e4
> --- /dev/null
> +++ b/datasrc/ueventd/queue-processor.c
> @@ -0,0 +1,116 @@
> +/* SPDX-License-Identifier: GPL-2.0-or-later */
> +
> +#include <sys/types.h>
> +#include <sys/stat.h>
> +#include <sys/wait.h>
> +
> +#include <stdlib.h>
> +#include <stdio.h>
> +#include <string.h>
> +#include <signal.h>
> +#include <dirent.h>
> +#include <fcntl.h>
> +#include <errno.h>
> +
> +#include "ueventd.h"
> +
> +static void event_handler(struct watch *queue, char *path) __attribute__((nonnull(1, 2)));
> +static void move_files(char *srcdir, char *dstdir) __attribute__((nonnull(1, 2)));
> +static void signal_unhandled_events(struct watch *queue) __attribute__((nonnull(1)));
> +
> +void event_handler(struct watch *queue, char *path)
Здесь оба указателя могут быть константными, т.к. данные не меняются и
дальше не передаются.
> +{
> + char *argv[] = { handler_file, path, NULL };
> + pid_t pid = vfork();
> +
> + if (pid < 0) {
> + err("fork: %m");
> +
> + } else if (!pid) {
> + execve(argv[0], argv, environ);
Компилятор не ругается здесь только потому, что подключен <unistd.h>
через "ueventd.h", а ругаться у него целых два повода (execve и
environ). Это я к тому, что в твоём заголовочном файле он подключен для
logging.c, а не для queue-processor.c. Согласно man 7 environ можно не
объявлять эту переменную в коде, если <unistd.h> подключается с
_GNU_SOURCE, т.е. как раз твой случай.
> + fatal("exec: %s: %m", argv[0]);
> + } else {
> + int status = 0;
> +
> + if (waitpid_retry(pid, &status, 0) != pid || !WIFEXITED(status))
> + info("%s: session=%lu: %s failed",
> + queue->q_name, session, handler_file);
Насчёт "session=%lu..." только лишь глядя в этот код понял, что и сам в
не публичном коде опрометчиво использую uint64_t с таким
форматированием, хотя везде по коду должно быть "session=" PRIu64 "...".
Нужно подключить заголовочный файл <inttypes.h> либо использовать
какое-то приведение типов. Пренебречь этим, как сейчас, можно только
полагаясь на конкретные платформы.
> + else
> + info("%s: session=%lu: %s finished with return code %d",
> + queue->q_name, session, handler_file, WEXITSTATUS(status));
> + }
> +}
> +
> +void move_files(char *srcdir, char *dstdir)
Здесь оба указателя тоже могут быть константными.
> +{
> + struct dirent *ent;
> + int srcfd, dstfd;
> +
> + if ((srcfd = open(srcdir, O_RDONLY | O_CLOEXEC)) < 0)
> + fatal("open: %s: %m", srcdir);
> +
> + errno = 0;
> + if ((dstfd = open(dstdir, O_RDONLY | O_CLOEXEC)) < 0) {
> + if (errno == ENOENT) {
> + if (mkdir(dstdir, 0755) < 0)
> + fatal("mkdir: %s: %m", dstdir);
> + dstfd = open(dstdir, O_RDONLY | O_CLOEXEC);
> + }
> + if (dstfd < 0)
> + fatal("open: %s: %m", dstdir);
> + }
> +
> + DIR *d = fdopendir(srcfd);
> + if (!d)
> + fatal("fdopendir: %m");
> +
> + while ((ent = xreaddir(d, srcdir)) != NULL) {
> + if (ent->d_name[0] != '.' && ent->d_type == DT_REG &&
Поле d_type заполняется не на всех системах (не на всех файловых
системах), доверять можно только d_name и d_ino. Если всё это происходит
на ramfs и есть уверенность, что в ней это поддерживается, то и нет
проблемы... пока в этот ramfs не смонтировать что-то ещё и не начать
использовать этот же код для другой файловой системы.
> + renameat(srcfd, ent->d_name, dstfd, ent->d_name) < 0)
> + fatal("rename `%s/%s' -> `%s/%s': %m", srcdir, ent->d_name, dstdir, ent->d_name);
> + }
> +
> + closedir(d);
> + close(dstfd);
> +}
> +
> +void signal_unhandled_events(struct watch *queue)
И здесь указатель может быть константным.
> +{
> + ssize_t len;
> +
> + len = write_loop(queue->q_parentfd,
> + (char *) &queue->q_watchfd, sizeof(queue->q_watchfd));
> + if (len < 0)
> + err("write(pipe): %m");
> +
> + info("%s: session=%lu: retry with the events remaining in the queue", queue->q_name, session);
> +}
Не углубляясь в код ueventd.c (только по названию и содержимому функции)
вообще нельзя понять, что она делает и причём тут PIPE. А всё потому,
что функция утилитарная и в "ueventd.h" поля структуры watch не имеют
комментариев.
Поэтому спрошу. Она сообщает о необработанных эвентах? Похоже, что через
PIPE родительскому процессу передаётся целое число (q_watchfd). Но
почему для передачи через PIPE тут используется write_loop()? Ведь в/в
через PIPE (даже неблокирующий) всегда транзакционен, если не превышает
PIPE_BUF.
> +
> +void process_events(struct watch *queue)
Похоже, тут тоже указатель может быть константным.
> +{
> + info("%s: session=%lu: processing events", queue->q_name, session);
> +
> + char *numenv = NULL;
> +
> + xasprintf(&numenv, "SESSION=%lu", session);
> + putenv(numenv);
Здесь возможна утечка: пропущен free(numenv), а когда numenv будет
освобождена?
> +
> + char *srcdir, *dstdir;
Для numenv есть инициализация, а тут нет, хотя использование одинаковое.
Нет предупреждений?
> +
> + xasprintf(&srcdir, "%s/%s", filter_dir, queue->q_name);
> + xasprintf(&dstdir, "%s/%s", uevent_dir, queue->q_name);
> +
> + move_files(srcdir, dstdir);
> +
> + if (!empty_directory(dstdir)) {
> + event_handler(queue, dstdir);
> +
> + if (!empty_directory(dstdir))
> + signal_unhandled_events(queue);
> + }
> +
> + free(srcdir);
> + free(dstdir);
> +
> + exit(0);
> +}
> [...]
--
WBR, Leonid Krivoshein.
next prev parent reply other threads:[~2023-05-15 4:38 UTC|newest]
Thread overview: 45+ messages / expand[flat|nested] mbox.gz Atom feed top
2023-05-04 13:42 [make-initrd] [PATCH 0/3] " Alexey Gladkov
2023-05-04 13:42 ` [make-initrd] [PATCH 1/3] " Alexey Gladkov
2023-05-05 3:08 ` Leonid Krivoshein
2023-05-05 17:02 ` Alexey Gladkov
2023-05-05 4:03 ` Leonid Krivoshein
2023-05-05 17:16 ` Alexey Gladkov
2023-05-05 5:21 ` Leonid Krivoshein
2023-05-05 17:24 ` Alexey Gladkov
2023-05-14 20:12 ` Leonid Krivoshein
2023-05-14 20:45 ` Alexey Gladkov
2023-05-14 20:57 ` Leonid Krivoshein
2023-05-15 8:52 ` Alexey Gladkov
2023-05-14 23:08 ` Leonid Krivoshein
2023-05-15 9:05 ` Alexey Gladkov
2023-05-15 0:47 ` Leonid Krivoshein
2023-05-15 9:12 ` Alexey Gladkov
2023-05-15 4:38 ` Leonid Krivoshein [this message]
2023-05-15 10:43 ` Alexey Gladkov
2023-05-18 6:39 ` Leonid Krivoshein
2023-05-18 7:05 ` Alexey Gladkov
2023-05-20 9:00 ` Leonid Krivoshein
2023-05-20 13:18 ` Alexey Gladkov
2023-05-20 15:17 ` Vladimir D. Seleznev
2023-05-20 17:23 ` Leonid Krivoshein
2023-05-20 18:51 ` Alexey Gladkov
2023-05-21 8:53 ` [make-initrd] [PATCH] ueventd: Don't use a epoll timeout when it's not needed Alexey Gladkov
2023-05-22 4:46 ` Leonid Krivoshein
2023-05-22 7:54 ` Alexey Gladkov
2023-05-22 9:19 ` Alexey Gladkov
2023-05-22 7:57 ` [make-initrd] [PATCH 1/2] ueventd: Fix memory leak Alexey Gladkov
2023-05-22 7:57 ` [make-initrd] [PATCH 2/2] ueventd: Change interface rd_asprintf_or_die Alexey Gladkov
2023-05-22 9:36 ` [make-initrd] [PATCH v2] " Alexey Gladkov
2023-05-20 16:37 ` [make-initrd] [PATCH 1/3] ueventd: Simplify call of the queue handler Alexey Gladkov
2023-05-20 16:37 ` [make-initrd] [PATCH 2/3] ueventd: Rename fd_list to fd_handler_list Alexey Gladkov
2023-05-20 16:37 ` [make-initrd] [PATCH 3/3] ueventd: Drop obsolete declarations Alexey Gladkov
2023-05-04 13:42 ` [make-initrd] [PATCH 2/3] Replace polld by uevent queue Alexey Gladkov
2023-05-04 13:42 ` [make-initrd] [PATCH 3/3] feature/kickstart: Reset rootdelay timer after kickstart Alexey Gladkov
2023-05-06 19:45 ` [make-initrd] ueventd: Add a prefix to the logging functions to avoid name collisions Alexey Gladkov
2023-05-06 19:45 ` [make-initrd] ueventd: Allow to configure the log destination Alexey Gladkov
2023-05-06 19:45 ` [make-initrd] ueventd: Pass the program name when initializing the logger Alexey Gladkov
2023-05-06 19:45 ` [make-initrd] ueventd: Rewrite logging function to make it more atomic Alexey Gladkov
2023-05-07 12:48 ` [make-initrd] [PATCH 0/3] Reimplement ueventd Alexey Gladkov
2023-05-13 11:50 ` Alexey Gladkov
2023-05-14 20:15 ` Leonid Krivoshein
2023-05-14 20:49 ` Alexey Gladkov
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=ecf9f7a7-5f84-adaa-c374-1d02c8a7ff76@gmail.com \
--to=klark.devel@gmail.com \
--cc=make-initrd@lists.altlinux.org \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Make-initrd development discussion
This inbox may be cloned and mirrored by anyone:
git clone --mirror http://lore.altlinux.org/make-initrd/0 make-initrd/git/0.git
# If you have public-inbox 1.1+ installed, you may
# initialize and index your mirror using the following commands:
public-inbox-init -V2 make-initrd make-initrd/ http://lore.altlinux.org/make-initrd \
make-initrd@lists.altlinux.org make-initrd@lists.altlinux.ru make-initrd@lists.altlinux.com
public-inbox-index make-initrd
Example config snippet for mirrors.
Newsgroup available over NNTP:
nntp://lore.altlinux.org/org.altlinux.lists.make-initrd
AGPL code for this site: git clone https://public-inbox.org/public-inbox.git