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

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

问题描述

这是关于 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/ 中).我猜想 thread-shared 信号量可能会在其内存段被删除时被破坏(不再被任何进程映射).我不确定这一点,它是特定于实现的行为,所以不要依赖这个.

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.

避免未定义行为.

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

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