minitalk/client.c
2024-07-27 14:43:47 +02:00

117 lines
2.2 KiB
C

/* ************************************************************************** */
/* */
/* ::: o_ :::::: ::: */
/* client.c :+: / :+::+: :+: */
/* +:+ > +:++:+ +:+ */
/* By: whaffman <whaffman@student.codam.nl> +#+ +:+ +#++#++:++#++ */
/* +#+ +#+#+ +#++#+ +#+ \o/ */
/* Created: 2024/07/18 16:28:03 by whaffman #+#+# #+#+# #+# #+# | */
/* Updated: 2024/07/27 14:43:17 by whaffman ### ### ### ### / \ */
/* */
/* ************************************************************************** */
#include <signal.h>
#include <unistd.h>
#define SLEEP 100
static volatile int g_ack = 0;
size_t ft_strlen(const char *s)
{
size_t length;
length = 0;
while (*s++)
length++;
return (length);
}
void ft_putstr(char *str)
{
write(1, str, ft_strlen(str));
}
int ft_isspace(int c)
{
return (' ' == c || '\f' == c || '\n' == c
|| '\r' == c || '\t' == c || '\v' == c);
}
int ft_isdigit(char c)
{
return (c >= '0' && c <= '9');
}
int ft_atoi(const char *nptr)
{
int sign;
int res;
while (ft_isspace(*nptr))
nptr++;
res = 0;
sign = 1;
while (*nptr == '-' || *nptr == '+')
{
if (*nptr == '-')
sign *= -1;
nptr++;
}
while (ft_isdigit(*nptr))
res = 10 * res + sign * (*nptr++ - '0');
return (res);
}
int send_byte(int pid, unsigned char c)
{
int i;
i = 0;
while (i < 8)
{
if ((c & 128) == 128)
kill(pid, SIGUSR1);
else
kill(pid, SIGUSR2);
c = c << 1;
usleep(SLEEP);
while (!g_ack)
pause();
g_ack = 0;
i++;
}
return (1);
}
int send_message(int pid, char *msg)
{
while (*msg)
{
send_byte(pid, *msg);
msg++;
}
send_byte(pid, '\0');
return (1);
}
void sig(int signum)
{
(void)signum;
g_ack = 1;
}
int main(int argc, char *argv[])
{
int pid;
if (argc != 3)
ft_putstr("Usage: ./client <pid> <message>");
pid = ft_atoi(argv[1]);
if (pid <= 1)
return (1);
g_ack = 0;
signal(SIGUSR1, sig);
send_message(pid, argv[2]);
return (0);
}