1

我有这个测试代码来使用 smartctl 命令。它打开一个管道,popen用于获取此smartctl命令的输出。

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

int main()
{
    cout << "Hello ! " << endl;
    FILE *fp;
    char path[1035];

    /* Open the command for reading. */
    fp = popen("smartctl -A /dev/sda", "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }

    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path), fp) != NULL) {
        printf("%s", path);
    }

    /* close */
    pclose(fp);
    return 0;
}

显然,运行该程序需要 root 权限,而对我来说使用的好处是功能。该程序使用什么功能以及如何设置它?

附带问题:我在这里使用了另一种方法更改可执行文件的所有权,但它不起作用。有人可以解释为什么吗?system如果我这样使用,同样的事情也不起作用system("smartctl -A /dev/sda > test.txt");

4

0 回答 0