switch to mmap - bsleep - Unnamed repository; edit this file 'description' to name the repository.
DIR Log
DIR Files
DIR Refs
DIR README
DIR LICENSE
---
DIR commit 93eeaeaabcd36f08039ac5ea94ea7e309f2eccb0
DIR parent dc93ba1a8438c25f25be6ddfb051d48b028f9171
HTML Author: kroovy <me@kroovy.de>
Date: Tue, 25 Feb 2025 00:25:30 +0100
switch to mmap
Diffstat:
M bsleep.c | 74 ++++++++-----------------------
1 file changed, 19 insertions(+), 55 deletions(-)
---
DIR diff --git a/bsleep.c b/bsleep.c
@@ -1,66 +1,30 @@
#define _POSIX_SOURCE
#include <signal.h>
-#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
-#include <sys/types.h>
+#include <sys/mman.h>
#include <unistd.h>
int
main(void)
{
- int i, in;
- pid_t pid;
- int fd[2];
- char c = ' ';
-
- if (pipe(fd) == -1) {
- printf("An error ocurred with opening the pipe\n");
- }
- if (signal(SIGCHLD, SIG_IGN) == SIG_ERR) {
- perror("signal");
- exit(EXIT_FAILURE);
- }
- pid = fork();
-
- switch (pid) {
- case -1:
- perror("fork");
- exit(EXIT_FAILURE);
-
- case 0:
- /* CHILD */
-
- /* setup */
- close(fd[1]);
-
- /* read button press + count seconds */
- for (i=1;;i++) {
- pread(fd[0], &c, sizeof(char), 0);
- printf("\r[ press 'b' to interrupt: %ds ] [ '%c' was pressed ] ", i, c); fflush(stdout);
- sleep(1);
- }
- /* cleanup */
- close(fd[0]);
- exit(EXIT_SUCCESS);
-
- default:
- /* PARENT */
-
- /* setup */
- close(fd[0]);
- system("/bin/stty raw -echo");
-
- /* handle button-press */
- while ((in = getchar()) != 'b') {
- write(fd[1], &in, sizeof(char));
- }
+ int i;
+ int *shared_memory = mmap(NULL, sizeof(char), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
+
+ pid_t pid = fork();
+
+ if (pid == 0) {
+ /* CHILD */
+ for (i=1;;i++) {
+ printf("\r[ press 'b' to interrupt: %ds ] [ '%c' was pressed ] ", i, *shared_memory); fflush(stdout);
+ sleep(1);
+ }
+ } else {
+ /* PARENT */
+ system("/bin/stty raw -echo");
+ while ((*shared_memory = getchar()) != 'b');
kill(pid, SIGKILL);
-
- /* cleanup */
- close(fd[1]);
- system("/bin/stty cooked echo");
- printf("\n");
- exit(EXIT_SUCCESS);
- }
+ system("/bin/stty cooked echo");
+ printf("\n");
+ }
}