// for child process pid_t pid = fork(); switch (pid) { case-1: { return-1; } case0: { std::cout << "this is child process" << std::endl; while (true) { // will core here, because tsk->ev_ is created in father-thread, not copyed, // so in child process, tsk->ev_ is nullptr tsk->print_str(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } default: { // this is father break; } } // end switch
while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); } return0; }
(gdb) bt #00x00007f4154e1a54din __lll_lock_wait () from /lib64/libpthread.so.0 #10x00007f4154e15e9bin _L_lock_883 () from /lib64/libpthread.so.0 #20x00007f4154e15d68in pthread_mutex_lock () from /lib64/libpthread.so.0 #30x000000000040128cin __gthread_mutex_lock (__mutex=0x1d2fc48) at /usr/include/c++/4.8.5/x86_64-unknown-linux-gnu/bits/gthr-default.h:748 #40x0000000000401730in std::mutex::lock (this=0x1d2fc48) at /usr/include/c++/4.8.5/mutex:134 #50x0000000000401f99in std::unique_lock<std::mutex>::lock (this=0x7fff168c43a0) at /usr/include/c++/4.8.5/mutex:511 #60x0000000000401b13in std::unique_lock<std::mutex>::unique_lock (this=0x7fff168c43a0, __m=...) at /usr/include/c++/4.8.5/mutex:443 #70x0000000000401988in TaskHandler::print_str (this=0x1d2fc38) at fork_copy_thread.cc:43 #80x00000000004013ffin main () at fork_copy_thread.cc:76 (gdb)
// for child process pid_t pid = fork(); switch (pid) { case-1: { return-1; } case0: { std::cout << "this is child process" << std::endl; while (true) { // will core here, because tsk->ev_ is created in father-thread, not copyed, // so in child process, tsk->ev_ is nullptr //tsk->print_str(); std::this_thread::sleep_for(std::chrono::seconds(1)); } } default: { // this is father break; } } // end switch
while (true) { std::this_thread::sleep_for(std::chrono::seconds(1)); } return0; }
简单解释一下修改了啥:
父进程启动一个线程,循环打印字符串
父进程 fork,子进程保持睡眠
验证子进程是否有线程打印字符串(如果复制了的话,理应会打印)
执行结果:
1 2 3 4 5 6 7
$ ./fork_copy_thread this threadid:139674369169152 run this threadid:139674369169152 run thisis child process this threadid:139674369169152 run this threadid:139674369169152 run this threadid:139674369169152 run