您的位置:首页 > 运维架构 > Shell

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

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

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

      脚本正文如下:(此时脚本名叫做"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中,用于后续处理(在这个例子中就是简单的输出到控制台).
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell C++ 脚本