免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3937 | 回复: 5
打印 上一主题 下一主题

[函数] 请教在重定向标准输入、输出时,exec函数族调用的问题。 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2003-04-15 21:49 |只看该作者 |倒序浏览
bc是linux下的高精度计算器语言,支持交互式操作。
同时,也支持如下操作方式:  bc  <infile   >;outfile
其中,infile中包含如下bc操作语句  a=1; print(a);
则outfile中的内容为1。

试想编程调用bc进行计算,故编程如下:


#include <stdio.h>;
#include <unistd.h>;

#define MAX_LINELEN 256
#define TMPDIR "/tmp/"

main(int argc,char *argv[])
{
        char *cmd;
        char *param;
        char *arg[10];
        char infname[MAX_LINELEN+1];
        char outfname[MAX_LINELEN+1];
        FILE *inf,*outf;
        int wgx;

        if (argc!=3)
        {
                printf("Command or parameter missing!\n";
                exit(0);
        }

        cmd=argv[1];
        param=argv[2];

        sprintf(infname,"%smy.in",TMPDIR);
        sprintf(outfname,"%smy.out",TMPDIR);

        inf=fopen(infname,"w";
        fprintf(inf,"%s",param);
        fclose(inf);

        inf=freopen(infname,"r",stdin);
        outf=freopen(outfname,"w",stdout);

        arg[0]=cmd;
        
        wgx=execv(cmd,arg);
        printf("%d\n",wgx);
        
}

编译后,生成可执行程序a.out,在bash下运行程序如下:
./a.out   bc   a=1\;print\(a\)\;

(注:分号、括号在bash下需先转义)
根据编程思路,输入、输出文件均能正常建立并打开,但execv(execvp)函数调用出错,变量wgx值为-1。

究竟错在何处,请大虾指点,万分感谢!!!

论坛徽章:
0
2 [报告]
发表于 2003-04-16 08:55 |只看该作者

请教在重定向标准输入、输出时,exec函数族调用的问题。

execv没有那么智能。在第一个参数中要包括路径。cmd应该是/usr/bin/bc,而不是bc。

论坛徽章:
0
3 [报告]
发表于 2003-04-17 13:38 |只看该作者

请教在重定向标准输入、输出时,exec函数族调用的问题。

好像不是这个原因。我进行相应的调试,结果依然如此。

论坛徽章:
0
4 [报告]
发表于 2003-04-17 18:00 |只看该作者

请教在重定向标准输入、输出时,exec函数族调用的问题。

int execv (const char *path, char *const *argv);

以上选自man execv
execv需要和程序完整名

你照楼上的方法做过了吗

论坛徽章:
0
5 [报告]
发表于 2003-04-17 18:05 |只看该作者

请教在重定向标准输入、输出时,exec函数族调用的问题。

arg参数格式错误。手册如是说:

……
The  execv and execvp functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program.  The first argument, by convention, should point to the file name associated  with the  file  being  executed.  The array of pointers must be terminated by a NULL pointer.
……

论坛徽章:
0
6 [报告]
发表于 2003-04-17 23:10 |只看该作者

请教在重定向标准输入、输出时,exec函数族调用的问题。

楼上的说得对,第二个参数还要是以NULL结尾的字符串数组。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP