我正在开发 C 函数来使用以下方式关闭我的嵌入式 Linux 系统 (Ubuntu)。
#include <stdlib.h>
int main()
{
system("shutdown -P now");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这种方法安全吗?
如果没有,有没有更好更安全的方法可以执行相同的任务?
#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 会忽略它。
| 归档时间: |
|
| 查看次数: |
1054 次 |
| 最近记录: |