Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the fork command work with a multi threaded application?

I tried to fork a multi threaded application. It seems fork hasn't replicate my second thread.

This is my code:

#include <stdlib.h>
#include <pthread.h>
#include <iostream>
#include <linux/unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>

using namespace std;

void Loop(const char* zThread)
{
    while (true)
    {
        sleep(2);
        cout << "LOOP : " << zThread << " : " << getpid() << endl;
    }
}

void *MyFunction(void *pData)
{
    Loop("Second");
};

int main()
{
    pthread_t thread1;

    pthread_create(&thread1, NULL, MyFunction, NULL);

    int iPID = fork();

    if (iPID == 0)
        cout << "Child : " << getpid() << endl;
    else
        cout << "Parent : " << getpid() << endl;

    Loop("First");

    return EXIT_SUCCESS;
};

It gives the following output, which does not contain any information written by the second thread of the child process.

test_1/ss> ./a.out
Parent : 11877
Child : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879

What happened to the second thread?

like image 253
Sujith Gunawardhane Avatar asked Jul 17 '14 14:07

Sujith Gunawardhane


2 Answers

Only the calling thread is forked.

From the docs:

A process shall be created with a single thread. If a multi-threaded process calls fork(), the new process shall contain a replica of the calling thread and its entire address space, possibly including the states of mutexes and other resources. Consequently, to avoid errors, the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.

like image 133
nos Avatar answered Oct 17 '22 05:10

nos


man fork

  • The child process is created with a single thread -- the one that called fork(). The entire vir- tual address space of the parent is replicated in the child, including the states of mutexes, con- dition variables, and other pthreads objects; the use of pthread_atfork(3) may be helpful for dealing with problems that this can cause.
like image 30
Slava Avatar answered Oct 17 '22 07:10

Slava