PDA

View Full Version : fork() and sockets



biosx
02-08-2002, 10:48 AM
I'm trying to get a grasp on socket programming in Linux. The thing is that my unix/linux programming skills aren't exactly what I thought they were. Oh well. I can pick up most everything except the fork() function. Here is the snippet I saw:



pid_t pid;

switch (pid = fork())
{
case -1:
/* Here pid is -1, the fork failed */
/* Some possible reasons are that you're */
/* out of process slots or virtual memory */
perror("The fork failed!");
break;

case 0:
/* pid of zero is the child */
/* Here we're the child...what should we do? */
/* ... */
/* but after doing it, we should do something like: */
_exit(0);

default:
/* pid greater than zero is parent getting the child's pid */
printf("Child's pid is %d\n",pid);
}


Now I can understand that it splits the one process into two processes. The PID of the child is zero and the PID of the parent is the old PID. Now it gets fuzzy with the switch() statement (which could be an if/else). What happens? Which executes when and why? Do both the parent and child go through the switch() at the same time? Does one go through and the other doesn't?

Please help, thanks

Salem
02-08-2002, 10:58 AM
> Do both the parent and child go through the switch() at the same time?
Logically, yes - you now have two processes, each with its own copy of the code, data and stack to play with.

In reality, only one thing happens at once, so typically one of them runs, the OS reshedules the tasks, then the other one runs.

But in any event, both tasks execute only one of the cases, its just a different case in each task

Strut
02-12-2002, 09:00 AM
Your using fork() to handle multiple connections right?

You most likely are, because thats what I've always seen it used as. There is a much better way to handle multiple connections, if you needed to.

I'm writing a MUD game, so multiple connections are imperiative. What I do is keep a list of all the socket descriptors. Then I cycle through each one and see what it needs. Its a rather complicated process to read in commands, and infomration and getting it all together. But I find it much more effecient that using fork(). Plus since fork() switches between them, and handles only one at once, if something goes wrong it could get stuck, or mess up.

But I guess it also dependson what kind of program your writing. All mud games are set up this way(to my knowledge, they are). I just thoughtI'd share some info because I felt like giving some out.

Bye!