From fc2201769e850bca4b718305a1f8e776f5d0786b Mon Sep 17 00:00:00 2001 From: Mattias Andrée Date: Sat, 4 Sep 2021 11:41:21 +0200 Subject: Use MSG_PEEK instead of sending unnecessary data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Mattias Andrée --- copier.c | 12 +++++++++--- editasroot.c | 6 ------ 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/copier.c b/copier.c index 3e7a6c6..5488f03 100644 --- a/copier.c +++ b/copier.c @@ -22,6 +22,7 @@ main(int argc, char *argv[]) path = argv[0]; parentfd = atoi(argv[1]); + /* Send content of file to parent */ filefd = open(path, O_RDWR); /* O_RDWR establishes that we can indeed write to the file */ if (filefd < 0) { fprintf(stderr, "%s: open %s O_RDWR: %s\n", argv0, path, strerror(errno)); @@ -37,13 +38,18 @@ main(int argc, char *argv[]) exit(1); } - r = read(parentfd, &b, 1); - if (r != 1) { - if (r) + /* Wait for parent to start sending the new file content, + * so that O_TRUNC does not cause the file to be truncated + * without new content being sent in case the parent exited + * abnormally. */ + r = recv(parentfd, &b, 1, MSG_PEEK); + if (r <= 0) { + if (r < 0) fprintf(stderr, "%s: read %s: %s\n", argv0, path, strerror(errno)); exit(1); } + /* Rewrite file with content sent from parent */ filefd = open(path, O_WRONLY | O_TRUNC); if (filefd < 0) { fprintf(stderr, "%s: open %s O_WRONLY|O_TRUNC: %s\n", argv0, path, strerror(errno)); diff --git a/editasroot.c b/editasroot.c index 09479f8..0a092cd 100644 --- a/editasroot.c +++ b/editasroot.c @@ -230,12 +230,6 @@ main(int argc, char *argv[]) /* Start file editor */ run_editor(editor, path, fds[0]); - /* Signal to child that editor exited as expected */ - if (write(fds[0], &(char){1}, 1) != 1) { - fprintf(stderr, "%s: write : %s", argv0, strerror(errno)); - exit(1); - } - /* Rewrite file from tmpfile and unlink tmpfile */ fd = open(path, O_RDONLY); if (fd < 0) { -- cgit v1.2.3-70-g09d2