我正在写一个C程序中我fork()
,exec()
和wait()
.我想把我执行的程序的输出写入文件或缓冲区.
例如,如果我exec ls
我想写入file1 file2 etc
缓冲区/文件.我认为没有办法读取标准输出,所以这是否意味着我必须使用管道?这里有一个我无法找到的一般程序吗?
R S*_*hko 86
用于将输出发送到另一个文件(我要忽略错误检查以关注重要细节):
if (fork() == 0)
{
// child
int fd = open(file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
dup2(fd, 1); // make stdout go to file
dup2(fd, 2); // make stderr go to file - you may choose to not do this
// or perhaps send stderr to another file
close(fd); // fd no longer needed - the dup'ed handles are sufficient
exec(...);
}
Run Code Online (Sandbox Code Playgroud)
要将输出发送到管道,您可以将输出读入缓冲区:
int pipefd[2];
pipe(pipefd);
if (fork() == 0)
{
close(pipefd[0]); // close reading end in the child
dup2(pipefd[1], 1); // send stdout to the pipe
dup2(pipefd[1], 2); // send stderr to the pipe
close(pipefd[1]); // this descriptor is no longer needed
exec(...);
}
else
{
// parent
char buffer[1024];
close(pipefd[1]); // close the write end of the pipe in the parent
while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*ler 15
你需要准确地决定你想做什么 - 最好更清楚地解释一下.
如果您知道要执行的命令的输出要转到哪个文件,则:
如果您希望父级读取子级的输出,请安排子级将其输出传递回父级.
归档时间: |
|
查看次数: |
89830 次 |
最近记录: |