程序向 shell脚本传递参数且获取shell的输出

3 篇文章 0 订阅

        这是上一篇博客的增强版.上一篇博客中,将向脚本的输入写死在了脚本中.问题是,我们通常遇到需要在程序中动态想脚本传递待处理的参数,然后经脚本的输出结果用于程序的下文.

       经过一段时间的调研,这个问题被圆满解决了,可能不能说是多么的优化,但是好歹是一种做法.写下来,以飨读者.

      脚本正文如下:(此时脚本名叫做"url.sh")

#!/bin/bash
printf $(echo -n $1 | sed 's/\\/\\\\/g;s/\(%\)\([0-9a-fA-F][0-9a-fA-F]\)/\\x\2/g')"\n"

在上面的脚本中,我仅仅传入了一个参数,就是$1.

        然后下面是程序的正文:

#include <pthread.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
using namespace std;
//参数cmdstring :脚本路径
//参数args         :传递给脚本的参数
//参数 buf          :保存脚本输出的变量
//参数 len          :buf的大小
int mysystem(const char* cmdstring, string args,char* buf, int len)
{
    int   fd[2];
     pid_t pid;
    int   n, count;
    memset(buf, 0, len);
    if (pipe(fd) < 0)
        return -1;
    if ((pid = fork()) < 0)
        return -1;
    else if (pid > 0)     /* parent process */
    {
        close(fd[1]);     /* close write end */
        count = 0;
        while ((n = read(fd[0], buf + count, len)) > 0 && count > len)
            count += n;
        close(fd[0]);
        if (waitpid(pid, NULL, 0) > 0)
            return -1;
    }
    else    /* child process */
    {
        close(fd[0]);     /* close read end */
        if (fd[1] != STDOUT_FILENO)
        {
            if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO)
            {
                return -1;
            }
            close(fd[1]);
        }
        if (execl("/bin/sh", "-c", cmdstring,args.c_str(),(char*)0) == -1)
        {
            cout<<"err"<<endl;
            return -1;
        }
    }
    return 0;
}
int main()
{
    char p[1024];                                                                      
    string test = "http://192.168.190.2/demo.cgi?method=tcp&tid=%E4%BD%A0%E4%BB%AC";    
    mysystem("/Data2Code/tmpTest/url.sh",test,p,1024);
    cout<<p;
    return 0;
}
                          
在main函数中,传递给参数test,让这个参数传入脚本,然后该脚本输出保存在p中,用于后续处理(在这个例子中就是简单的输出到控制台).

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值