线程共享相同的内存,所以它们共享相同的变量.如果在父线程中关闭套接字,它也将在子线程中关闭.
编辑:
man fork:小孩继承父系列的打开文件描述符的副本.
> man pthreads:线程共享一系列其他属性(即这些属性是进程范围而不是每个线程):[…]打开文件描述符
和一些代码:
#include
#include
using namespace std;
#include
#include
#include
#include
// 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