|
#ifndef IO_H
|
|
#define IO_H
|
|
#include <unistd.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <sys/select.h>
|
|
#include <errno.h>
|
|
|
|
int *get_readable(int *fds)
|
|
{
|
|
fd_set read_fds;
|
|
static int readable[10];
|
|
memset(readable, 0, sizeof(readable));
|
|
FD_ZERO(&read_fds);
|
|
int max_fd = -1;
|
|
for (int i = 0; fds[i] != -1; i++)
|
|
{
|
|
FD_SET(fds[i], &read_fds);
|
|
if (fds[i] > max_fd)
|
|
max_fd = fds[i];
|
|
}
|
|
int ready = select(max_fd + 1, &read_fds, NULL, NULL, NULL);
|
|
if (ready == -1)
|
|
{
|
|
perror("select");
|
|
return readable;
|
|
}
|
|
int readable_index = 0;
|
|
readable[readable_index] = -1;
|
|
for (int i = 0; fds[i] != -1; i++)
|
|
{
|
|
if (FD_ISSET(fds[i], &read_fds))
|
|
{
|
|
readable[readable_index] = fds[i];
|
|
readable_index++;
|
|
readable[readable_index] = -1;
|
|
}
|
|
}
|
|
|
|
return readable;
|
|
}
|
|
|
|
void msleep(uint time)
|
|
{
|
|
usleep(time * 1000);
|
|
}
|
|
|
|
char *read_line(int fd, size_t limit)
|
|
{
|
|
char *buffer = (char *)malloc(limit + 1);
|
|
ssize_t length = read(fd, buffer, limit);
|
|
if (length > 0)
|
|
{
|
|
buffer[length] = 0;
|
|
return buffer;
|
|
}
|
|
else if (length == 0)
|
|
{
|
|
printf("Child process closed");
|
|
}
|
|
else
|
|
{
|
|
perror("read");
|
|
}
|
|
return NULL;
|
|
}
|
|
char *write_str(int fd, char *data)
|
|
{
|
|
write(fd, data, strlen(data));
|
|
}
|
|
|
|
void type(int fd, char *text)
|
|
{
|
|
while (*text)
|
|
{
|
|
char content[] = {*text, 0};
|
|
write(fd, content, strlen(content));
|
|
text++;
|
|
msleep(100);
|
|
}
|
|
}
|
|
|
|
#endif
|