gpt4 book ai didi

c - 在 C 中保留 RAM

转载 作者:IT王子 更新时间:2023-10-28 23:33:05 25 4
gpt4 key购买 nike

我需要有关如何编写一个 C 程序的想法,该程序保留指定数量的 MB RAM 直到一个键 [例如。在 Linux 2.6 32 位系统上按下任意键]。

*
/.eat_ram.out 200

# If free -m is execute at this time, it should report 200 MB more in the used section, than before running the program.

[Any key is pressed]

# Now all the reserved RAM should be released and the program exits.
*

这是程序的核心功能 [保留 RAM] 我不知道该怎么做,从命令行获取参数、打印 [任何键被按下] 等等对我来说都不是问题。

关于如何做到这一点的任何想法?

最佳答案

您想使用 malloc() 来执行此操作。根据您的需要,您还需要:

  1. 将数据写入内存,以便内核真正保证它。您可以为此使用 memset()。
  2. 防止内存被分页(交换),mlock()/mlockall() 函数可以帮助您。
  3. 告诉内核您实际上打算如何使用内存,这是通过 posix_madvise() 完成的(这比显式的 mlockall() 更可取)。

在大多数情况下,malloc() 和 memset()(或 calloc() 有效地做同样的事情)将满足您的需求。

最后,当然,您想在不再需要内存时释放()内存。

关于c - 在 C 中保留 RAM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2398905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com