2

我正在尝试使用自定义输入从 C++ 调用 shell 脚本。我能做的是:

void dostuff(string s) {
    system("echo " + s + " | myscript.sh");
    ...
}

当然,转义 s 是相当困难的。有没有办法可以将 s 用作 myscript.sh 的标准输入?即,像这样:

void dostuff(string s) {
    FILE *out = stringToFile(s);
    system("myscript.sh", out);
}
4

2 回答 2

2

system重新分配标准输入并在调用后恢复它的简单测试:

#include <cstdlib>     // system
#include <cstdio>      // perror
#include <unistd.h>    // dup2
#include <sys/types.h> // rest for open/close
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>

#include <iostream>

int redirect_input(const char* fname)
{
    int save_stdin = dup(0);

    int input = open(fname, O_RDONLY);

    if (!errno) dup2(input, 0);
    if (!errno) close(input);

    return save_stdin;
}

void restore_input(int saved_fd)
{
    close(0);
    if (!errno) dup2(saved_fd, 0);
    if (!errno) close(saved_fd);
}

int main()
{
    int save_stdin = redirect_input("test.cpp");

    if (errno)
    {
        perror("redirect_input");
    } else
    {
        system("./dummy.sh");
        restore_input(save_stdin);

        if (errno) perror("system/restore_input");
    }

    // proof that we can still copy original stdin to stdout now
    std::cout << std::cin.rdbuf() << std::flush;
}

效果很好。我用这样一个简单的dummy.sh脚本对其进行了测试:

#!/bin/sh
/usr/bin/tail -n 3 | /usr/bin/rev

注意最后一行将标准输入转储到标准输出,所以你可以像这样测试它

./test <<< "hello world"

并期待以下输出:

won tuodts ot nidts lanigiro ypoc llits nac ew taht foorp //    
;hsulf::dts << )(fubdr.nic::dts << tuoc::dts    
}
hello world
于 2012-10-06T22:52:24.727 回答
0

使用popen

void dostuff(const char* s) {
  FILE* f = fopen(s, "r");
  FILE* p = popen("myscript.sh", "w");
  char buf[4096];
  while (size_t n = fread(buf, 1, sizeof(buf), f))
    if (fwrite(buf, 1, n, p) < n)
      break;
  pclose(p);
}

您需要添加错误检查以使其健壮。

请注意,我更喜欢 a const char*,因为它更灵活(与 以外的东西一起使用std::string)并且与内部发生的事情相匹配。如果您真的喜欢std::string,请这样做:

void dostuff(const std::string& s) {
    FILE* f = fopen(s.c_str(), "r");
    ⋮

另请注意,选择 4096 字节缓冲区是因为它与大多数系统上的页面大小相匹配。这不一定是最有效的方法,但它适用于大多数用途。我发现 32 KiB 是我自己在笔记本电脑上进行的不科学测试中的最佳选择,所以你可能想玩一玩,但如果你对效率很认真,你会想要切换到异步 I/O,然后开始开始写入n后立即读取n+1

于 2012-10-06T23:51:20.767 回答