gpt4 book ai didi

c - 从本应作为 init 进程运行的 C 程序关闭 Linux

转载 作者:太空狗 更新时间:2023-10-29 15:25:54 25 4
gpt4 key购买 nike

我正在编写一个 C 程序来在 Linux 系统上执行各种操作,然后将其关闭。该程序将使用 PID 为 1 的命令行选项 init=/path/to/program 启动,因此,我不能使用 execl("/sbin/poweroff", "poweroff", NULL);,因为 poweroff 命令不会关闭系统本身,它会要求 PID 为 1 的进程来执行此操作。那么init用什么代码来关闭系统呢?

最佳答案

为什么 poweroff 不起作用?

许多程序假定内核已使用 init 作为 PID 1 启动。在许多系统上,init 是指向 systemd 的符号链接(symbolic link)程序;类似地,在这些系统上,poweroff 通常是指向 systemctl 程序的符号链接(symbolic link)。

在您的设置中,systemd 从未启动,因为您设置了自定义 init=/path/to/program 内核参数行。这就是 poweroff 命令不起作用的原因:systemctl 正在尝试联系从未创建的 systemd 实例。

如何在没有systemd的情况下关机。

reboot 函数在 Linux Programmer's Manual 中有描述。 .在 glibc 下,您可以传递 RB_POWER_OFF 宏常量来执行重启。

请注意,如果 reboot 之前没有调用 sync,数据可能会丢失。

Linux 中使用 glibc:

#include <unistd.h>
#include <sys/reboot.h>

sync();
reboot(RB_POWER_OFF);

另见

How to restart Linux from inside a C++ program?

关于c - 从本应作为 init 进程运行的 C 程序关闭 Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39403774/

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