I know calling fork() sys_call
from a thread is a bad idea.
However, what will happen if a thread creates a new process using fork()
?
The new process will be the child of the main thread that created the thread. I think.
If its parent finishes first, the new process will be attached to init process. And its parent is main thread, not the thread that created it.
Correct me if I am wrong.
#include <stdio.h>
#include <pthread.h>
int main ()
{
thread_t pid;
pthread_create(&(pid), NULL, &(f),NULL);
pthread_join(tid, NULL);
return 0;
}
void* f()
{
int i;
i = fork();
if (i < 0) {
// handle error
} else if (i == 0) // son process
{
// Do something;
} else {
// Do something;
}
}
The fork( ) system call creates an exact duplicate of the address space from which it is called, resulting in two address spaces executing the same code. Problems can occur if the forking address space has multiple threads executing at the time of the fork( ).
RETURN VALUE Upon successful completion, fork() returns 0 to the child process and returns the process ID of the child process to the parent process. Otherwise, -1 is returned to the parent process, no child process is created, and errno is set to indicate the error.
A fork gives you a brand new process, which is a copy of the current process, with the same code segments. As the memory image changes (typically this is due to different behavior of the two processes) you get a separation of the memory images (Copy On Write), however the executable code remains the same.
It's safe to fork in a multithreaded program as long as you are very careful about the code between fork and exec. You can make only re-enterant (aka asynchronous-safe) system calls in that span.
The new process will be the child of the main thread that created the thread. I think.
fork
creates a new process. The parent of a process is another process, not a thread. So the parent of the new process is the old process.
Note that the child process will only have one thread because fork
only duplicates the (stack for the) thread that calls fork
. (This is not entirely true: the entire memory is duplicated, but the child process will only have one active thread.)
If its parent finishes first, the new process will be attached to init process.
If the parent finishes first a SIGHUP
signal is sent to the child. If the child does not exit as a result of the SIGHUP
it will get init
as its new parent. See also the man pages for nohup
and signal(7)
for a bit more information on SIGHUP
.
And its parent is main thread, not the thread that created it.
The parent of a process is a process, not a specific thread, so it is not meaningful to say that the main or child thread is the parent. The entire process is the parent.
One final note: Mixing threads and fork must be done with care. Some of the pitfalls are discussed here.
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