Linux安全弹出设备的小程序(c++)

由于使用了Ubuntu17 版本,发现有一些小问题,其中一个让我很诧异,当移动硬盘连接之后,只有Unmount的选项,没有Safe Remove的选项,这可真是可怕,于是自己动手写了一个小程序,有兴趣的可以看一下,过两天上github。

程序简介:

运行之后,列出已挂载的设备并输出名称,然后等待用户输入想要移除的设备名(部分即可,但是不要出现重的),输入之后,如果没有找到这个设备名,则输出错误信息。找到这个设备之后,调用udisksctl命令,首先unmount这个设备,等待三秒,(以防万一)然后给这个设备断电。程序中的who.log文件目录希望用户可以自己调整。更加细致的优化,等我有时间再说。

下面是源码

额#include <iostream>
#include <fstream>
#include<string>
#include <unistd.h>
using namespace std;
char str[256];
string Mount_on;
string name;
int main() {
    remove("/home/allen/files/log/who.log");
    system("df >>/home/allen/files/log/who.log");
    cout<<"List the mounted devices :"<<endl<<endl;
    ifstream fs("/home/allen/files/log/who.log");
    fs.getline(str,256);
    while(fs.getline(str,256))
    {
        string tmp=str;
        if(tmp.find("%")!=-1)
        {

            cout<<tmp.substr(tmp.find("%")+2)<<endl;
        }
    }
    //getchar();
    string ins="udisksctl unmount -b ";
    fs.close();
    ifstream fs1("/home/allen/files/log/who.log");
    cout<<"Please input part of name the divece you want to power-off"<<endl;
    cin>>name;
    while(fs1.getline(str,256))
    {
        string tmp=str;
        //cout<<tmp<<endl;
        if(tmp.find(name.c_str())!=-1)
        {
            Mount_on=tmp.substr(0,tmp.find(" "));
            cout<<Mount_on<<endl;
        }
    }
    if(Mount_on=="")
    {
        cout<<"Havan't found this device ,Please view ~/files/log/who.log to check "<<endl;
        return -1;
    }
    ins+=Mount_on;
    system(ins.c_str());
    sleep(3);
    ins="udisksctl power-off -b ";
    ins+=Mount_on;
    system(ins.c_str());
    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值