Hi there!
I'm writing a little program that needs to fork 2 times and then the child has to run some code. It should be quite an easy task, but my child seems to die right after the first line of code it runs..
Code:
int j = 0;
for (j = 0; j < nrOfClients; j++) // let's assume nrOfClients = 2
{
int iPid = fork();
switch ( iPid ) {
case 0 :
clientTCP();
case -1:
perror("Error while forking");
exit(1);
//default:
//printf("Child %d created \n", j);
}
}
sleep(30000);
Code:
void clientTCP(void)
{
printf("prints this \n");
int sock;
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
{
printf("but doesn't come here");
perror("Error creating socket");
exit(1);
}
printf("or here.");
int k;
for (k = 0; k < nrOfRequests; k++)
{
char messageReceived[nrOfBytes];
write(sock, messageOut, nrOfBytes);
printf("clientTCP 2");
int bytesReceived;
bzero(&messageReceived, sizeof(messageReceived));
if ((bytesReceived = read(sock, messageReceived, nrOfBytes)) == 0)
{
fprintf(stderr, "The server has terminated the connection. \n");
close(sock);
exit(0);
}
printf("clientTCP 3");
printf("Child %d received %d bytes \n", getpid(), bytesReceived);
}
It's probably a stupid mistake, but I'd appreciate it if someone can help me get further.