简体   繁体   中英

How to create create subprocess with a FILE* as its stdin, stdout or stderr?

If there is a series of FILE pointer which point FILE data("object"). I want to create a subprocess and set this subprocess's stdin stdout and stderr to these FILE pointer. What can I do?

If there is no such function, I can create one, but I don't know how.

If it is necessary, access the member of FILE is also permitted.

There is some headers provided by C standard library like m, But they only support IO-redirect with file-descriptor.

The only thing I have is non-null FILE pointers.

I would like this function do almost exactly same as subprocess.run in Python.

int subprocess_run(char *filename, char **args, FILE *std_in, FILE *std_out, FILE *stderr);

Two options: either using the traditional fork(), or using the new 'spawn'

Using fork

int subprocess_run(char *filename, char **args, FILE *std_in, FILE *std_out, FILE *std_err);

   fflush(std_out) ;
   fflush(std_err) ;
   pid_t pid = fork() ;

   if ( !pid ) {
      // Child process, setup files, exec program, ...

      dup2(fileno(std_in)), STDIN_FILENO) ;
      dup2(fileno(std_out)), STDOUT_FILENO) ;
      dup2(fileno(std_err)), STDERR_FILENO) ;
      execvp(filename, args) ;
      perror("exevcp failed") ;

   } else if ( pid == -1 ) {
       // Error
       ...
   } else {
       // Parent
       ...
   } ;
}

Note that 'args' should include program names as argv[0], as per execvp requirements. Otherwise, you will have to construct new array.

Using posix_spawn

The 'posix_spawn' provides interface to achieve the same as above, but require significantly more complex setup (for the problem described here). It provides minor advantage for certain system, as it can reduce overhead of forking. Take a look at man posix_spawn if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM