C函数关闭linux系统

raj*_*123 5 c embedded-linux

我正在开发 C 函数来使用以下方式关闭我的嵌入式 Linux 系统 (Ubuntu)。

#include <stdlib.h>

int main() 
{
    system("shutdown -P now");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这种方法安全吗?
如果没有,有没有更好更安全的方法可以执行相同的任务?

Cin*_*its 2

男人重启(2)

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

int main () {
    sync();    // If reboot() not preceded by a sync(), data will be lost.
    setuid(0); // set uid to root, the running uid must already have the
               // appropriate permissions to do this.
    reboot(RB_AUTOBOOT); // note, this reboots the system, it's not as
    return(0);           // graceful as asking the init system to reboot.
}
Run Code Online (Sandbox Code Playgroud)

在 systemd 之前,您有时也可以逃脱:

int main() {
    sync();
    kill(1, SIGTERM);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这种方法在程序在单个 shell 下运行的嵌入式系统上更为普遍,但杀死 initd 也很有效。请注意,在使用 systemd/upstart 的较新的 GNU/Linux 上,SIGTERMsystemd 会忽略它。