[英]Redirecting using dup2() and execve()
I want to write a function void redirect(char *msg) in C that opens a file named "hello.txt" for writing, create a child process via fork(), then use output redirection (via the dup2() function) to redirect the child's standard output to your open file. I want to write a function void redirect(char *msg) in C that opens a file named "hello.txt" for writing, create a child process via fork(), then use output redirection (via the dup2() function) to将孩子的标准 output 重定向到您打开的文件。 Then, have the child use execve to call the "/bin/echo" program and give it the message your were passed in order to write to the file.
然后,让孩子使用 execve 调用“/bin/echo”程序并给它你传递的消息以便写入文件。
This is what I am having now:这就是我现在所拥有的:
void redirect(char *msg){
int fd = fopen("hello.txt", 'wb');
pid_t child = fork();
if(child == 0){
dup2(fd, STDOUT_FILENO);
execve("/bin/echo", msg, environ);
}
}
and it is not working, I don't know what to pass into dup2 and execve.它不起作用,我不知道将什么传递给 dup2 和 execve。
fopen
returns value of type FILE *
, which is not valid UNIX file descriptor. fopen
返回FILE *
类型的值,这是无效的 UNIX 文件描述符。 Use open
for this, check out man 2 open
.为此使用
open
,查看man 2 open
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.