Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
- #include <pthread.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <termios.h>
- #include <sys/select.h>
- #include <sys/ioctl.h>
- #include <cstring>
- using namespace std;
- typedef struct Arguments {
- bool* flag;
- int* fd;
- } arguments;
- int _kbhit() {
- static const int STDIN = 0;
- static bool initialized = false;
- if (! initialized) {
- termios term;
- tcgetattr(STDIN, &term);
- term.c_lflag &= ~ICANON;
- tcsetattr(STDIN, TCSANOW, &term);
- setbuf(stdin, NULL);
- initialized = true;
- }
- int bytesWaiting;
- ioctl(STDIN, FIONREAD, &bytesWaiting);
- return bytesWaiting;
- }
- void *tread(void *args) {
- puts("write thread started");
- arguments *argument = (arguments*)args;
- char msg[] = "LETI 2018 OS";
- while (*(argument->flag)) {
- write(*(argument->fd), msg, strlen(msg));
- printf("Writed: %s\n", msg);
- fflush(stdout);
- sleep(1);
- }
- printf("write thread finished\n");
- fflush(stdout);
- pthread_exit(NULL);
- }
- int main() {
- char fifo_name[] = "current_fifo_name";
- pthread_t threadInit;
- bool flag = true;
- arguments args;
- int fd;
- unlink(fifo_name);
- if(mkfifo(fifo_name, 0777) == -1)
- perror("mkfifo");
- fd = open(fifo_name, O_WRONLY | O_NONBLOCK);
- while((fd==-1)&&(!_kbhit())){
- fd = open(fifo_name, O_WRONLY | O_NONBLOCK);
- perror("open:");
- sleep(1);
- }
- args.fd = &fd;
- args.flag = &flag;
- if(pthread_create(&threadInit, NULL, &tread, (void*)&args))
- EXIT_FAILURE;
- getchar();
- flag = false;
- pthread_join(threadInit, NULL);
- close(fd);
- unlink(fifo_name);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment