
// read and write with 2 threads

#include <assert.h>
#include <pthread.h>
#include <err.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define BUFFS 1024

int fd;

void * thr_read (void * arg)
{
	int ret;
	char buff[BUFFS];
	arg++; // just to avoid warning

	// copy the socket to the standard output
	while (1)
	{
		ret = read (fd, buff, BUFFS);
		if (ret == -1) err (1, "read");
		warnx ("read: read %d bytes", ret);
		if (ret == 0) break;
		ret = write (1, buff, ret);
		if (ret == -1) err (1, "write");
	}
	warnx ("read: exiting");
	return 0;
}

void * thr_write (void * arg)
{
	int ret;
	char buff[BUFFS];
	arg++; // just to avoid warning

	// copy standard input to the socket
	while (1)
	{
		ret = read (0, buff, BUFFS);
		if (ret == -1) err (1, "read");
		warnx ("write: read %d bytes", ret);
		if (ret == 0) break;
		ret = write (fd, buff, ret);
		if (ret == -1) err (1, "write");
	}
	warnx ("write: exiting");
	return 0;
}

int main ()
{
	struct sockaddr_in addr;
	int ret;
	pthread_t tid1, tid2;

	fd = socket (AF_INET, SOCK_STREAM, 0);
	if (fd == -1) err (1, "socket");

	addr.sin_family = AF_INET;
	addr.sin_port = htons (1234);
	//addr.sin_addr.s_addr = htonl (0x1f00001);
	addr.sin_addr.s_addr = htonl (INADDR_LOOPBACK);

	ret = connect (fd, (struct sockaddr *) &addr, sizeof (addr));
	if (ret == -1) err (1, "connect");

	warnx ("connected!\n");

	errno = pthread_create (&tid1, 0, thr_read, 0);
	if (errno != 0) err (1, "pthread_create read");
	errno = pthread_create (&tid2, 0, thr_write, 0);
	if (errno != 0) err (1, "pthread_create write");

	errno = pthread_join (tid1, 0);
	if (errno != 0) err (1, "pthread_join");
	warnx ("main: thread %ld terminates", (long) tid1);

	errno = pthread_join (tid2, 0);
	if (errno != 0) err (1, "pthread_join");
	warnx ("main: thread %ld terminates", (long) tid2);

	close (fd);
	return 0;
}

