在fork()之后将stdout重定向到文件

编程入门 行业动态 更新时间:2024-10-27 02:24:26
本文介绍了在fork()之后将stdout重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在一个简单的shell上工作,但是现在我只是想了解重定向.我只是对ls命令进行硬编码,现在尝试将其写入文件.当前,ls运行,并且创建了输出文件,但是输出仍然转到stdout,并且该文件为空白.我对为什么感到困惑.预先感谢.

I'm working on a simple shell, but right now I am just trying to understand redirection. I'm just hard coding an ls command and trying to write it to a file for now. Currently, the ls runs, and the output file is created, but the output still goes to stdout and the file is blank. I'm confused as to why. Thanks in advance.

这是我的代码:

int main() { int ls_pid; /* The new process id for ls*/ char *const ls_params[] = {"/bin/ls", NULL}; /* for ls */ int file; /* file for writing */ /* Open file check user permissions */ if (file = open("outfile", O_WRONLY|O_CREAT) == -1) /* , S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP */ { perror("Failed to open file"); _exit(EXIT_FAILURE); } ls_pid = fork(); /* Create new process for ls */ if (ls_pid == -1) /* error check */ { perror("Error forking ls (pid == -1)"); _exit(EXIT_FAILURE); } else if (ls_pid == 0) /* Child of ls */ { /* Redirect output to file */ if (dup2(file, STDOUT_FILENO) == -1) /* STDOUT_FILENO = 1 */ { perror("Error duping to file"); _exit(EXIT_FAILURE); } close(file); execvp("ls", ls_params); /* create the sort process */ /* execlp("ls", "ls", NULL); */ /* if this does not end the program, something is wrong */ perror("Exec failed at sort"); _exit(EXIT_FAILURE); } else /* ls parent (1) */ { /* wait for child */ if (wait(NULL) == -1) { perror("fork failed on parent"); _exit(EXIT_FAILURE); } } }

推荐答案

我看不到任何问题.我自己尝试了您的代码.而且有效!我的简化代码如下:

I don't see any problem. I tried your code by myself. And it works! My simplified code looks like:

int main(void) { int fd; char* const param[] = {"/bin/ls", NULL}; fd = open("outfile", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); if (fd < 0) { perror("open failed\n"); exit(0); } pid_t pid = fork(); if (pid < 0) { perror("fork failed\n"); exit(0); } else if (pid == 0) { dup2(fd, STDOUT_FILENO); close(fd); execvp("ls", param); } else { wait(NULL); } }

我编译一个执行程序,然后在输出文件中找到预期的结果.

I compile an execute it, and find the expected results in outfile.

唯一的区别是我使用S_IRUSER | S_IWUSER权限选项,因为否则打开失败.我在您的代码中看到了类似的内容,但是您以某种方式对其进行了注释...

The only difference is that I feed open with the S_IRUSER | S_IWUSER permission options since otherwise the open fails. I see similar thing in your code but somehow you commented them...

更多推荐

在fork()之后将stdout重定向到文件

本文发布于:2023-10-09 10:36:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1475506.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:后将   重定向   文件   fork   stdout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!