如果不在 C 中的信号量上调用 sem_destroy() 会发生什么? [英] What may happen if sem_destroy() is not invoked on a semaphore in C?

查看:106
本文介绍了如果不在 C 中的信号量上调用 sem_destroy() 会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是关于C语言中的信号量编程.

This is regarding to semaphore programming in C language.

    sem_t mutex;
    .
    .
    int main()
    {
        sem_init(&mutex, 0, 1);
        .
        .
        .
        .
        sem_destroy(&mutex);
        return 0;
    }

如果我在最后的程序中没有使用 sem_destroy(),它可能会导致什么影响?

If I do not use sem_destroy() at the last of my programs, what implications it may cause?

推荐答案

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

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

在使用之前,必须初始化一个未命名的信号量使用 sem_init(3).然后可以使用它进行操作sem_post(3) 和 sem_wait(3).当信号量不再需要,并且在它所在的内存之前解除分配,应使用销毁信号量sem_destroy(3).

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).

所以你应该在适当的时候调用sem_destroy;不要冒险发生系统范围的资源泄漏.sem_destroy(3) 的 BTW 文档说明:

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

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

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.

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

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.

也使用 proc(5).

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

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.

避免未定义的行为.

这篇关于如果不在 C 中的信号量上调用 sem_destroy() 会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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