C++でシェルコマンドを実行するにはどうすればよいですか?

C++におけるシェルコマンドの実行方法は次のとおりです。

  1. システム()
  2. システム()
  3. エルマイナスエル
#include <cstdlib>

int main() {
    int result = system("ls -l");
    return 0;
}

system()関数は命令実行の戻り値を返します。この戻り値からコマンドの実行が成功したかどうかを判断できます。

  1. popen()関数
  2. popen()
  3. ls -l
#include <cstdio>

int main() {
    FILE* pipe = popen("ls -l", "r");
    if (pipe == nullptr) {
        // 处理错误
    }

    char buffer[128];
    while (fgets(buffer, sizeof(buffer), pipe) != nullptr) {
        // 处理输出
    }

    pclose(pipe);
    return 0;
}

popen()関数はファイルストリームを返し、ストリームを読み出してコマンドの出力を取り出すことができます。

  1. フォーク
  2. exec()
  3. fork()
  4. exec()
  5. ls -l
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    pid_t pid = fork();
    if (pid == 0) {
        // 子进程
        execl("/bin/ls", "ls", "-l", nullptr);
        // 如果exec函数执行失败,需要处理错误
    } else if (pid > 0) {
        // 父进程
        int status;
        waitpid(pid, &status, 0);
        // 处理子进程的结束状态
    } else {
        // fork函数执行失败,处理错误
    }

    return 0;
}

fork()関数によって子プロセスが生成され、子プロセスはexecl()関数によってls -lコマンドを実行します。

上記はシェルコマンドを実行する一般的な方法の一部で、それらを使用する際には安全性や移植性を考慮し、コマンドインジェクションなどのセキュリティ問題を防ぐためにユーザー入力のコマンドの使用を避ける必要があります。

bannerAds