0

我有一个程序可以读取文件,对其进行处理并将结果放入输出文件中。当我有一个参数(输入文件)时,我创建输出文件并将其写入内容。

我制作了一个 fork() 以便将标准输出重定向到 write() 内容。

char *program;

program = malloc(80);

sprintf(program, "./program < %s > %s", inputFile, outputFile);   
int st;
switch (fork()) {
  case -1:
       error("fork error");
         case 0:
           /* I close the stdout */
           close (1);

             if (( fd = open(outputfile, O_WRONLY | O_CREAT , S_IWUSR | S_IRUSR | S_IRGRP)==-1)){

                 error("error creating the file \n");
                 exit(1);
             }

             execlp("./program", program,  (char *)0);

             error("Error executing program\n");
              default:
          // parent process - waits for child's end and ends
            wait(&st);
            exit(0);
     //*****************

              }

使用 < > 标准输入正确创建子节点,并创建标准输出文件。但是,孩子永远不会结束,当我杀死父亲时,输出文件是空的,所以代码没有执行。

怎么了?谢谢!

4

1 回答 1

1

exec 系列中的函数不理解重定向

您调用的方式是execlp向程序传递一个参数:./program < %s > %s. 没错,一个论点。当然,execlp不知道重定向是什么,也不知道program.

我会将您的所有代码替换为:

char *program = malloc(LEN);

snprintf(program, LEN, "./program < %s > %s", inputFile, outputFile);  
system(program);
于 2012-04-04T16:38:35.977 回答