如果我不销毁信号灯,会发生什么? [英] What may happen if I don't destroy a semaphore?

查看:114
本文介绍了如果我不销毁信号灯,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在最后一个程序中不使用sem_destroy,它可能会带来什么影响?会发生一些严重的问题吗?

解决方案

它是特定于操作系统的.在Linux上,阅读 sem_overview(7);实际上,您处于未指定的情况.但是,文档说

在使用前,必须初始化未命名的信号量 使用sem_init(3).然后可以使用 sem_post(3)和sem_wait(3).当信号量不再 必需,并且在其所在的内存之前 释放后,应使用以下命令销毁信号量 sem_destroy(3).

因此,您应在适当的时候致电sem_destroy ;不必冒全系统资源泄漏的风险. sem_destroy(3)的BTW文档告诉:

未命名的信号灯应在之前使用sem_destroy()销毁 它所在的内存被释放.未能做到这一点 可能会导致某些实现上的资源泄漏.

对于命名的信号灯,情况有所不同(它们位于/dev/shm/中).我猜想线程共享的信号量在删除其内存段时可能会被破坏(任何进程都不再映射).我不确定这是实现特定的行为,所以不要依赖于此.

还使用 proc(5).

>

所以可能发生的是整个系统范围内的 资源泄漏,您不想要它.您可能需要重新启动才能将其删除.顺便说一句,您可以使用 strace(1)来找出实际的系统调用,您可以查看GNU glibc (或其他一些代码)的源代码libc,例如 musl-libc )-也许是Linux内核-可以了解更多有关实现特定行为的信息. /p>

避免未定义的行为 .

If I do not use sem_destroy at the last of my programs, what implications it may cause? Can some serious problems occur?

解决方案

It is operating system specific. On Linux, read sem_overview(7); actually you are in an unspecified case. However, the documentation says

Before being used, an unnamed semaphore must be initialized using sem_init(3). It can then be operated on using sem_post(3) and sem_wait(3). When the semaphore is no longer required, and before the memory in which it is located is deallocated, the semaphore should be destroyed using sem_destroy(3).

so you should call sem_destroy when appropriate; don't risk having a system-wide resource leak. BTW documentation of sem_destroy(3) tells:

An unnamed semaphore should be destroyed with sem_destroy() before the memory in which it is located is deallocated. Failure to do this can result in resource leaks on some implementations.

For named semaphores, things are different (they sit in /dev/shm/). I guess that a thread-shared semaphore might be destroyed when its memory segment is removed (no more mapped by any process). I am not sure of this and it is implementation specific behavior, so don't rely on this.

Use also proc(5).

So what may happen is a system-wide resource leak and you don't want it. You might need to reboot to remove it. BTW, you could use strace(1) to find out the actual syscalls involved, and you could look into the source code of your GNU glibc (or some other libc, like musl-libc) - and perhaps of the Linux kernel- to understand more the implementation specific behavior.

Avoid undefined behavior.

这篇关于如果我不销毁信号灯,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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