Question:Recall that when a program has only one main thread and fork is called, the child process created by fork will also have only one thread; What if we put fork into a multi-threaded program? Let's try it out: Case (1) fork before creating a child threadCode: #include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { fork(); pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; } Result: The forked child process will also create its own child thread ( Case (2) fork after creating a child threadCode: #include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); fork(); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; } Result: After creating a child thread, a child process is created. At this time, the fork child process will only execute the code after fork ( Case (3) fork in child threadCode: #include <stdio.h> #include <pthread.h> #include <unistd.h> void* pthread_fun(void* arg) { fork(); printf("fun = %d\n", getpid()); pthread_exit(NULL); } int main() { pthread_t id; pthread_create(&id, NULL, pthread_fun, NULL); printf("main_pid = %d\n", getpid()); pthread_join(id, NULL); return 0; } result: in conclusion:In which thread is fork, the child process created after fork will use this thread as its main thread and execute the code after this thread This is the end of this article about fork in multi-threading under Linux. For more relevant Linux multi-threading fork content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: What are inline elements and block elements?
>>: Detailed explanation of common usage of pseudo-classes before and after in CSS3
Demand background A statistical interface, the fr...
This article example shares the specific code of ...
<br />For an article on a content page, if t...
Table of contents Preface 1. Trigger Overview 2. ...
Table of contents 1. Configure bridging and captu...
Development environment windows Development Tools...
Azure Container Registry is a managed, dedicated ...
The notepad program is implemented using the thre...
Let’s take a look first. HTML source code: XML/HT...
Table of contents Show Me The Code Test the effec...
Nginx hides version number In a production enviro...
Installation environment: CentOS7 64-bit MINI ver...
1. Set up Chinese input method 2. Set the double ...
Network Communication Overview When developing an...
If the program service is deployed using k8s inte...