首页 > 解决方案 > 关闭linux系统的C函数

问题描述

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

#include <stdlib.h>

int main() 
{
    system("shutdown -P now");
    return 0;
}

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

标签: cembedded-linux

解决方案


手动重启(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.
}

预系统化,你有时也可以逃脱:

int main() {
    sync();
    kill(1, SIGTERM);
    return 0;
}

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


推荐阅读