c - execl 不要离开子进程

标签 c fork

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

我创建了一个 fork() 以便将 stdout 重定向为 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);
     //*****************

              }

使用 < > stdin 和 stdout 文件正确创建子级。 但是, child 永远不会结束,当我杀死父亲时,输出文件是空的,因此代码没有执行。

发生了什么事? 谢谢!

最佳答案

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

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

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

char *program = malloc(LEN);

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

关于c - execl 不要离开子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10015439/

相关文章:

由于 getchar 导致崩溃

c - 如何使用 fork 将多条记录从 parent 传递给 child

c++ - 在 Linux 中将 fork() + execlp 与 boost::asio 一起使用时解决重用错误

c - 理解Linux中的fork()

c++ - OpenLDAP API 搜索

c - 为什么链接顺序与外部变量很重要?

perl fork 远程运行时无法正常工作(通过 ssh)

C - 两个进程读取同一个文件

C编程数组大层次

sql - 如何使用 C 从 .csv 文件加载到 SQL 数据库