user3799906
user3799906

Reputation: 61

fork() flow in C

I am having a little trouble with understanding execution flow of fork(). My main question is that when fork() is called does the calling process pause execution flow, or continue execution? Here is an example of what I'm working on

for (i = 0; i < hosts; i++)
{
    if (fork() == 0)
    {
       forward_data(client_sock, remote_sock[i]);           
    }
}

Here I use the fork() function to create separate processes that handle connections between remote hosts. The function forward_data() sends data from client_sock to remote_sock, and I am designing the program to send to multiple hosts at the same time.

Upvotes: 2

Views: 336

Answers (2)

user3793679
user3793679

Reputation:

First, as noted elsewhere, fork() makes a copy of the current process, and then both the new and the old process continue after the fork() returns -- the new process will see fork() return 0, the old process will see fork() return the pid of the new (child) process.

In what you've written, the original process will spawn hosts children, and each child will run forward_data(). If forward_data() returns, then each child will then spawn hosts - 1 grandchildren, who will in turn each spawn hosts - 2 further greatgrandchildren and so on.

Second, the short answer to the question "does the calling process pause execution flow, or continue execution?" is yes. The longer answer is that the calling process may or may not execute at the same time as the newly created process, you cannot tell and it may be different every time -- if you care, then you need to use some IPC mechanism to synchronise as required.

Third, since the question is tagged "multithreading", if the old process is running more than one pthread, then the new process inherits all the mutexes, conditions etc of the old process, in the state they were in when fork() was called. However, the new process has only one pthread, and that is a copy of the pthread in the old process which executed the fork().

Upvotes: 1

Havenard
Havenard

Reputation: 27844

fork() will duplicate the process and both processes (original and clone) will continue to execute from there, the only difference is that in the parent process, fork() will return the PID of the new process that was created (or -1 if error), while in the child process fork() will have returned 0.

It doesn't quite count as multithreading as once this split happens, the processes are no longer in the same virtual memory space.

Upvotes: 2

Related Questions