c - 关闭linux系统的C函数
问题描述
我正在开发 C 函数以使用以下方式关闭我的嵌入式 Linux 系统(Ubuntu)。
#include <stdlib.h>
int main()
{
system("shutdown -P now");
return 0;
}
这种方法安全吗?
如果没有,有没有更好更安全的方法可以执行相同的任务?
解决方案
#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
会忽略它。
推荐阅读
- vue.js - 如何在 vue.js datepicker 中设置出生日期和死亡日期的日期范围?
- android - 打开 BottomSheetDialogFragment 时禁用中断
- react-native - React Native 崩溃 IllegalArgumentException 无法在 com.facebook.react.bridge.Arguments.fromBundle 转换类 android.net.Uri$HierarchicalUri
- javascript - Nuxt.js 显示错误通知而不是页面
- python - 如何解决这个问题“ValueError: no enough values to unpack (expected 5, got 4)”?
- algorithm - 没有雪崩效应的哈希函数?
- asp.net-core - ASP.Net Core 中 InMemoryDatabase 的依赖注入代码
- android - TextView 动画 - 淡入、等待、自动淡出一段时间 Duration
- excel - 将值复制到多列上插入的空白行中
- django - 带有 UDP 套接字的 Django - 我应该使用什么,Twisted Plugin 或 Django Channels?