Last active
October 28, 2019 20:53
-
-
Save cpebble/19736aa516e896ae0e09834e83d90ec8 to your computer and use it in GitHub Desktop.
KageNuPlx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define _POSIX_C_SOURCE 1 | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <signal.h> | |
#include <string.h> | |
#include <sys/wait.h> | |
#include <sys/types.h> | |
#include <assert.h> | |
// | |
// Helper func | |
int file_pipes(FILE* files[2]){ | |
// Array for fd | |
int fds[2]; | |
// Åben pipes | |
assert(pipe(fds) == 0); | |
// Nu får vi bare file-objector | |
FILE *read_end = fdopen(fds[0], "r"); | |
FILE *write_end = fdopen(fds[1], "w"); | |
files[0] = read_end; | |
files[1] = write_end; | |
if (read_end == NULL || write_end == NULL) | |
return 1; | |
return 0; | |
} | |
// Handler for recognizing timeout | |
char timeout; | |
void handler(int signum){ | |
switch(signum){ | |
case SIGALRM: | |
timeout = 1; | |
break; | |
case SIGUSR1: | |
timeout = 0; | |
break; | |
} | |
} | |
char *tfgets(char *s, int size, FILE *stream){ | |
timeout = 0; | |
// This needs to wait five seconds then return | |
// make two children. One for fgets, one for sleeping | |
signal(SIGUSR1, handler); | |
signal(SIGALRM, handler); | |
pid_t fget_pid; | |
alarm(5); | |
FILE *files[2]; | |
assert(file_pipes(files) == 0); | |
if (( fget_pid = fork()) == 0){ | |
// Time to reading child | |
fclose(files[0]); | |
char buf[size]; | |
memset(buf, 0, size); | |
fgets(buf, size, stream); | |
// We need to send signal before writing to avoid blocking | |
kill(getppid(), SIGUSR1); | |
fwrite(buf, sizeof(char), size, files[1]); | |
fclose(files[1]); | |
exit(0); | |
} | |
fclose(files[1]); | |
pause(); | |
if(timeout){ | |
return NULL; | |
} else { | |
fread(s, sizeof(char), size, files[0]); | |
fclose(files[0]); | |
} | |
//return 0; | |
return s; | |
} | |
int main(){ | |
printf("Enter your name: "); | |
fflush(stdout); | |
char s[64]; | |
char* read = tfgets(s, 64, stdin); | |
if(read == NULL){ | |
printf("\nTimed out\n"); | |
} | |
else{ | |
printf("Hello %s", s); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment