在Linux中创建新线程复制文件描述符和套接字描述符?
发布时间:2021-01-12 14:42:12 所属栏目:Linux 来源:互联网
导读:每个人都知道一个监听套接字连接的进程的经典模型,并分派一个新进程来处理每个新的连接.通常的做法是让父进程立即在新创建的套接字上调用close,减少句柄数,以便只有子对一个新的套接字有一个句柄. 我已经看到,Linux中进程和线程的唯一区别是线程共享相同的内
每个人都知道一个监听套接字连接的进程的经典模型,并分派一个新进程来处理每个新的连接.通常的做法是让父进程立即在新创建的套接字上调用close,减少句柄数,以便只有子对一个新的套接字有一个句柄. 我已经看到,Linux中进程和线程的唯一区别是线程共享相同的内存.在这种情况下,我假设产生一个新的线程来处理新的连接也会重复文件描述符,并且还需要“父”线程关闭它的套接字的副本? 解决方法线程共享相同的内存,所以它们共享相同的变量.如果在父线程中关闭套接字,它也将在子线程中关闭.编辑: man fork:小孩继承父系列的打开文件描述符的副本. 和一些代码: #include <cstring> #include <iostream> using namespace std; #include <errno.h> #include <fcntl.h> #include <pthread.h> #include <unistd.h> // global variable int fd = -1; void * threadProc(void * param) { cout << "thread: begin" << endl; sleep(2); int rc = close(fd); if (rc == -1) { int errsv = errno; cout << "thread: close() failed: " << strerror(errsv) << endl; } else { cout << "thread: file is closed" << endl; } cout << "thread: end" << endl; } int main() { int rc = open("/etc/passwd",O_RDONLY); fd = rc; pthread_t threadId; rc = pthread_create(&threadId,NULL,&threadProc,NULL); sleep(1); rc = close(fd); if (rc == -1) { int errsv = errno; cout << "main: close() failed: " << strerror(errsv) << endl; return 0; } else { cout << "main: file is closed" << endl; } sleep(2); } 输出为: thread: begin main: file is closed thread: close() failed: Bad file descriptor thread: end (编辑:4S站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- Handling of asynchronous events---reference
- LINUX入门:Linux RedHat无法安装软件问题(No p
- linux – sed:如何删除匹配包含正斜杠的模式的行
- LINUX教程:CentOS 7 升级内核
- 什么时候需要curl_global_init()?
- linux – 为什么将’script’重定向到/ dev / nu
- Linux:将100万个文件移动到基于前缀的创建文件夹
- linux – 我可以在KDE中找到一个合适的平铺窗口管
- 如何将activerecord结果转换为包含root的哈希数组
- OpenCV在与anaconda的Linux上使用python无法正常
热点阅读