Question on select() : why am I getting absurd output ?
Manish Jain
invalid.pointer at gmail.com
Sun Jan 15 16:18:46 UTC 2012
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 at gmail.com
More information about the freebsd-questions
mailing list