I'm writing a simple chat client in C++ on linux to connect to a win32 chat server on my computer also written in C++. I'm confident that the server works but the chat client is giving me some trouble. I'm forking the chat client and have one process dealing with incoming messages and another dealing with sending messages. I'm using two pipes in the chat client so each process can tell the other when it has terminated so the other process can go ahead and terminate. The pipes don't seem to be working though and I'm not sure where I'm going wrong. If you guys could take a look at my code I'd appreciate it. Maybe one of you will notice something I'm not doing right. Here's my code:
#define ChildRead pipefd1[0]
#define ChildWrite pipefd2[1]
#define ParentRead pipefd2[0]
#define ParentWrite pipefd1[1]
int main()
{
int nret, theSocket, theMode = 1, pipefd1[2], pipefd2[2];
struct sockaddr_in server;
char buf[2] = {0}, message[999] = {0}, ipAddy[20]= {0}, scrName[20] = {0};
pid_t childpid;
printf("Enter the IP address to connect to.\n\n");
scanf("%s", ipAddy);
printf("\nEnter your screen name.\n\n");
scanf("%s", scrName);
theSocket = socket(AF_INET, SOCK_STREAM, 0);
if(theSocket < 0)
printf("\nCouldn't create socket\n");
memset(&server, 0, sizeof(server));
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(ipAddy);
server.sin_port = htons(8888);
printf("\nAttempting to connect to %s\n", ipAddy);
nret = connect(theSocket, (struct sockaddr *)&server, sizeof(server));
if(nret < 0)
printf("\nCouldn't connect\n");
ioctl(theSocket, FIONBIO, &theMode);
printf("\nConnected to server!\n\n");
memset(message, 0, strlen(message));
pipe(pipefd1);
pipe(pipefd2);
fcntl(ParentRead, F_SETFL, O_NONBLOCK);
fcntl(ParentWrite, F_SETFL, O_NONBLOCK);
fcntl(ChildRead, F_SETFL, O_NONBLOCK);
fcntl(ChildWrite, F_SETFL, O_NONBLOCK);
childpid = fork();
if(childpid == 0)
{
close(ParentRead);
close(ParentWrite);
while(1)
{
read(ChildRead, &buf, 1);
if(buf[0] == 'q')
{
close(ChildRead);
close(ChildWrite);
close(theSocket);
exit(0);
}
if((nret = recv(theSocket, message, 999, 0)) < 1)
continue;
if(message[7] == '~' && message[8] == 'q')
{
printf("\nChat server disconnected..\n");
write(ChildWrite, "q\0", 1);
close(ChildRead);
close(ChildWrite);
close(theSocket);
exit(0);
}
printf("%s\n", message);
memset(message, 0, strlen(message));
}
}
else
{
strcpy(message, scrName);
strcpy(&message[strlen(message)], ": ");
close(ChildWrite);
close(ChildRead);
while(1)
{
read(ParentRead, &buf, 1);
if(buf[0] == 'q')
{
close(ParentRead);
close(ParentWrite);
close(theSocket);
exit(0);
}
scanf("%s", &message[strlen(message)]);
if(strcmp(&message[strlen(scrName) + 2], "~q\0") == 0)
{
write(ParentWrite, "q\0", 1);
close(ParentRead);
close(ParentWrite);
close(theSocket);
exit(0);
}
send(theSocket, message, strlen(message), 0);
memset(&message[strlen(scrName) + 2], 0, strlen(&message[strlen(scrName) + 2]));
}
}
return 0;
}