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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With