套接字描述符的影响两次关闭了多线程程序中的错误 [英] Impact of socket descriptor closed twice bug in multithreaded program

查看:61
本文介绍了套接字描述符的影响两次关闭了多线程程序中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

fd = open("file", O_RDONLY);
if (fd < 0) exit(1);

while((res = read(fd, buf, sizeof(buf)))){
if (res < 0){
close(fd);
fprintf(stderr, "Read error!\n");
break;
} else {
printf("Read %zd bytes\n", res);
}
}
close (fd);

在单线程程序中,这是一个明显的错误:"fd"被两次关闭.此错误在多线程程序中可能产生什么影响?

In the single-threaded program this is an obvious bug: 'fd' is being closed twice. What could be the impact of this bug in a multithreaded program?

推荐答案

可以是任何东西.没有可靠的方法来预测污染"食品的效果.在多线程程序中共享资源.

It could be anything. There's no reliable way to predict the effect of "contaminating" shared resources in a multi-threaded program.

最明显的问题是,您可能会在第一次关闭后但在第二次关闭之前关闭出于某些重要目的而打开了另一个线程的套接字.但是,如果不了解该代码,就无法预测某些片段代码在这种情况下会做什么.

The most obvious problem would be that you might close a socket that another thread had opened for some important purpose after your first close but before your second close. But there's no way you can predict what some piece code will do under those circumstances without understanding that code.

仅作为一个示例,您可能通常会过早地终止与远程服务器的连接,从而导致服务器处理部分请求而不是完整的请求.如果不了解所使用的协议,就无法知道部分请求可能会做什么.

As just one example, you might prematurely normally terminate a connection to a remote server, causing the server to process a partial request instead of a complete one. There's no way to know what that partial request might do without understanding the protocol being used.

这是一个更糟糕的情况:

Here's an even worse scenario:

  1. 此线程关闭描述符4.
  2. 日志记录线程打开本地文件并获取描述符4.
  3. 此线程再次关闭描述符4.(错误.)
  4. 另一个线程打开与不受信任服务器的套接字连接,并获取描述符4.
  5. 日志记录线程再次运行,并将敏感信息写入描述符4.

糟糕.我们只是将高度敏感的信息发送到随机的远程连接.

Oops. We just sent highly-sensitive information to a random remote connection.

这篇关于套接字描述符的影响两次关闭了多线程程序中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆