[英]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").如果有一系列 FILE 指针指向 FILE data("object")。 I want to create a
subprocess
and set this subprocess's stdin stdout and stderr
to these FILE pointer.我想创建一个
subprocess
并将这个subprocess's stdin stdout and stderr
设置为这些 FILE 指针。 What can I do?我能做些什么?
If there is no such function, I can create one, but I don't know how.如果没有这样的function,我可以创建一个,但我不知道如何。
If it is necessary, access the member of FILE is also permitted.如果有必要,也允许访问 FILE 的成员。
There is some headers provided by C standard library like m, But they only support IO-redirect with file-descriptor. C 标准库提供了一些头文件,例如 m,但它们仅支持带文件描述符的 IO 重定向。
The only thing I have is non-null FILE pointers.我唯一拥有的是非空文件指针。
I would like this function do almost exactly same as subprocess.run in Python.我希望这个 function 与 Python 中的 subprocess.run 几乎完全相同。
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'两种选择:要么使用传统的 fork(),要么使用新的 'spawn'
Using fork
使用
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.请注意,根据 execvp 要求,“args”应包括程序名称为 argv[0]。 Otherwise, you will have to construct new array.
否则,您将不得不构建新数组。
Using posix_spawn
使用
posix_spawn
The 'posix_spawn' provides interface to achieve the same as above, but require significantly more complex setup (for the problem described here). 'posix_spawn' 提供了实现与上述相同的接口,但需要更复杂的设置(对于此处描述的问题)。 It provides minor advantage for certain system, as it can reduce overhead of forking.
它为某些系统提供了较小的优势,因为它可以减少分叉的开销。 Take a look at
man posix_spawn
if needed.如果需要,请查看
man posix_spawn
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.