fork() and sockets
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:
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?
switch (pid = fork())
/* 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!");
/* pid of zero is the child */
/* Here we're the child...what should we do? */
/* ... */
/* but after doing it, we should do something like: */
/* pid greater than zero is parent getting the child's pid */
printf("Child's pid is %d\n",pid);
Please help, thanks
> 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
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.