2012-04-04 62 views
0

我有一个程序读取一个文件,对待它并把结果放在一个输出文件中。当我有一个参数(输入文件)时,我创建输出文件并将其写入内容。execl不要离开孩子

我已经做了一个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); 
    //***************** 

       } 

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

发生了什么事? 谢谢!

+0

我会做这与'开放()'和'DUP2()'和'EXEC()',而不是试图用'<' and '>'为IO重定向。 – Flexo 2012-04-04 16:38:46

+0

谢谢!两种解决方案都有效 – drules 2012-04-04 17:25:29

回答

1

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

您打电话给execlp的方式,您将一个参数传递给您的程序:./program < %s > %s。这是对的,有一个论点。当然,execlp不知道重定向是什么,program也不知道。

我会取代所有的代码:

char *program = malloc(LEN); 

snprintf(program, LEN, "./program < %s > %s", inputFile, outputFile); 
system(program); 
+0

我同意你的诊断,但我没有在建议的解决方案上出售 - dup2似乎是一个更简洁的方法。 – Flexo 2012-04-04 16:41:16

+0

@awoodland为什么更清洁?离开重定向到shell可能是最简单的 - 这是shell的目的。当然,它不是很有效率,也不是便携式的,而是由3条线组成。 – cnicutar 2012-04-04 16:42:07

+0

嵌套壳内东西深感到肮脏。除了时髦的shell的非优雅失败(如果它会失败,我宁愿有一个编译时错误比一个奇怪的运行时问题),它很容易受到邪恶的东西,例如,如果outputFile有一个'somepath; rm -rf〜',或者更糟。 – Flexo 2012-04-04 16:46:46