Chinaunix

标题: 请教在重定向标准输入、输出时,exec函数族调用的问题。 [打印本页]

作者: wypwgx    时间: 2003-04-15 21:49
标题: 请教在重定向标准输入、输出时,exec函数族调用的问题。
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。

究竟错在何处,请大虾指点,万分感谢!!!
作者: kj501    时间: 2003-04-16 08:55
标题: 请教在重定向标准输入、输出时,exec函数族调用的问题。
execv没有那么智能。在第一个参数中要包括路径。cmd应该是/usr/bin/bc,而不是bc。
作者: wypwgx    时间: 2003-04-17 13:38
标题: 请教在重定向标准输入、输出时,exec函数族调用的问题。
好像不是这个原因。我进行相应的调试,结果依然如此。
作者: 无双    时间: 2003-04-17 18:00
标题: 请教在重定向标准输入、输出时,exec函数族调用的问题。
int execv (const char *path, char *const *argv);

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

你照楼上的方法做过了吗
作者: JohnBull    时间: 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.
……
作者: kj501    时间: 2003-04-17 23:10
标题: 请教在重定向标准输入、输出时,exec函数族调用的问题。
楼上的说得对,第二个参数还要是以NULL结尾的字符串数组。




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2