I am trying to create a socket programming server to handle multiple clients at the same time using fork().. But I am not able to implement it properly.I have been trying for a
The main problem you have is that ==
has higher precedence than =
, so this line:
if(pid=fork()==-1)
is assigning the result of fork() == -1
to pid
, which isn't what you want: it'll always be 0
when fork()
succeeds, in both the child and the parent. You need to use:
if((pid = fork()) == -1)
You should also close(new)
in the parent after the fork()
- the child owns that socket now. If you want to send the textual version of the counter, you need to use snprintf()
to convert it to text. The child should also exit after it's finished - the easiest way to do that in your code is to break out of the loop. After these corrections, the inner loop in your server looks like:
for(;;)
{
new = accept(sockid, (struct sockaddr *)&clientaddr, &len);
if ((pid = fork()) == -1)
{
close(new);
continue;
}
else if(pid > 0)
{
close(new);
counter++;
printf("here2\n");
continue;
}
else if(pid == 0)
{
char buf[100];
counter++;
printf("here 1\n");
snprintf(buf, sizeof buf, "hi %d", counter);
send(new, buf, strlen(buf), 0);
close(new);
break;
}
}