Skip site navigation (1)Skip section navigation (2)
Date:      Sun, 15 Jan 2012 21:18:59 +0530
From:      Manish Jain <invalid.pointer@gmail.com>
To:        freebsd-questions@freebsd.org
Subject:   Question on select() : why am I getting absurd output ?
Message-ID:  <4F12F56B.8030904@gmail.com>

Next in thread | Raw E-Mail | Index | Archive | Help

Hi All,

I was trying to write a small demo code using the select() system call. 
Here are the sources :

#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <iostream>
#include <cstring>
#include <cassert>

int nice_child(int * fd, int * fd_close)
{
	close(fd[0]);
	close(fd_close[0]);
	close(fd_close[1]);

	char buffer[32];
	
	while (1)
	{
		sleep(3);
		strcpy(buffer, "I love my wife !");
		write(fd[1], buffer, strlen(buffer) + 1);
	}

	return 0;
}

int naughty_child(int * fd, int * fd_close)
{
	close(fd[0]);
	close(fd_close[0]);
	close(fd_close[1]);

	char buffer[32];
	
	while (1)
	{
		sleep(4);
		strcpy(buffer, "I love your wife !");
		write(fd[1], buffer, strlen(buffer) + 1);
	}

	return 0;
}

int main()
{
	int fd_nice[2];
	int fd_naughty[2];

	pipe(fd_nice);
	pipe(fd_naughty);

	if (fork() == 0)
	{
		return nice_child(fd_nice, fd_naughty);
	}
	else
	{
		if (fork() == 0)
		{
			return naughty_child(fd_naughty, fd_nice);
		}
	}

	close(fd_nice[1]);
	close(fd_naughty[1]);

	fd_set fdset;
	char buffer[64];
	int fd = (*fd_naughty > *fd_nice) ? *fd_naughty : *fd_nice;

	FD_ZERO(&fdset);
	FD_SET(fd_nice[0], &fdset);
	FD_SET(fd_naughty[0], &fdset);

	while (1)
	{
		int result = select(fd + 1, &fdset, 0, 0, 0);
		assert(result > 0);

		if (FD_ISSET(fd_nice[0], &fdset))
		{
			int result = read(fd, buffer, sizeof(buffer));
			buffer[result] = 0;

			std::cout << "Nice child sent : " << buffer << std::endl;
		}

		if (FD_ISSET(fd_naughty[0], &fdset))
		{
			int result = read(fd, buffer, sizeof(buffer));
			buffer[result] = 0;

			std::cout << "Naughty child sent : " << buffer << std::endl;
		}
	}

	return 0;
}

I was expecting the output to be like :

Nice child sent : I love my wife !
Naughty child sent : I love your wife !
Nice child sent : I love my wife !

But what I actually get is :

Nice child sent : I love your wife !
Nice child sent : I love your wife !
Nice child sent : I love your wife !
Nice child sent : I love your wife !
Nice child sent : I love your wife !
Nice child sent : I love your wife !

Can somebody throw some light on what might be wrong ?


Thank you &
Regards

Manish Jain
invalid.pointer@gmail.com




Want to link to this message? Use this URL: <http://docs.FreeBSD.org/cgi/mid.cgi?4F12F56B.8030904>