管道自定义stdin到C ++中的系统调用 [英] Pipe custom stdin to system call in C++

查看:204
本文介绍了管道自定义stdin到C ++中的系统调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从自定义输入调用C ++的shell脚本。我可以做的是:

I'm trying to call a shell script from C++ with custom input. What I could do is:

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

当然,逃脱是相当困难的。有没有办法,我可以使用s作为stdin的myscript.sh?也就是说,像这样:

Of course, escaping s is quite difficult. Is there a way that I can use s as stdin for myscript.sh? Ie, something like this:

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


推荐答案

重新分配stdin的简单测试并在系统调用后恢复它:

A simple test to reassign stdin and restore it after the system call:

#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 脚本测试它:

Works out nicely. I tested it with a simple dummy.sh script like this:

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

注意最后一行将标准输入转储到标准输出,它像

Note the last line dumps standard input to standard output, so you could test it like

./test <<< "hello world"

并期待以下输出:

won tuodts ot nidts lanigiro ypoc llits nac ew taht foorp //    
;hsulf::dts << )(fubdr.nic::dts << tuoc::dts    
}
hello world

这篇关于管道自定义stdin到C ++中的系统调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆