c - 使用主函数参数给定的名称将标准输出重定向到文本文件
问题描述
我的任务有问题。我必须更改代码。我必须修改上面的代码,以便子进程将其标准输出重定向到具有主函数参数传递的名称的文本文件。
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main ()
{
int fds[2];
pid_t pid;
/* Create a pipe. File descriptors for the two ends of the pipe are placed in fds. */
/* TODO add error handling for system calls like pipe, fork, etc. */
pipe (fds);
/* Fork a child process. */
pid = fork ();
if (pid == (pid_t) 0) {
/* This is the child process. Close our copy of the write end of the file descriptor. */
close (fds[1]);
/* Connect the read end of the pipe to standard input. */
dup2 (fds[0], STDIN_FILENO);
/* Replace the child process with the "sort” program. */
execlp ("sort", "sort", NULL);
} else {
/* This is the parent process. */
FILE* stream;
/* Close our copy of the read end of the file descriptor. */
close (fds[0]);
/* Convert the write file descriptor to a FILE object, and write to it. */
stream = fdopen (fds[1], "w");
fprintf (stream, "This is a test.\n");
fprintf (stream, "Hello, world.\n");
fprintf (stream, "My dog has fleas.\n");
fprintf (stream, "This program is great.\n");
fprintf (stream, "One fish, two fish.\n");
fflush (stream);
close (fds[1]);
/* Wait for the child process to finish. */
waitpid (pid, NULL, 0);
}
return 0;
}
解决方案
推荐阅读
- java - Android 应用程序是否可以使用来自另一个应用程序的数据?
- c# - 即使没有对包的引用,也需要 Nuget 包
- c++ - Shamir Secret Sharing 中的模数和反模数问题
- firebase - Vue页面如何获取开头的数据
- python - 我似乎无法找到一种方法来获取 Pyqtgraph 中 ScatterPlotItem 的所有点的列表
- bots - 用户进入组时如何触发方法?
- python - 在 Linux 中以编程方式检查特定类型的设备
- google-apps-script - Google 表格脚本编辑器仅查看
- opengl - 更好地了解阴影痤疮
- python-3.x - 使用 Anaconda 管理 python 安装设置 Hydrogen 和 Atom