我正在写一个C程序,其中Ifork()
、exec()
和wait()
.我想将我执行的程序的输出写入文件或缓冲区.
例如,如果我执行ls
,我想将file1 file2 etc
写入缓冲区/文件.我不认为有一种方法可以阅读stdout,那么这是否意味着我必须使用管道?这里有没有我找不到的一般程序?
我正在写一个C程序,其中Ifork()
、exec()
和wait()
.我想将我执行的程序的输出写入文件或缓冲区.
例如,如果我执行ls
,我想将file1 file2 etc
写入缓冲区/文件.我不认为有一种方法可以阅读stdout,那么这是否意味着我必须使用管道?这里有没有我找不到的一般程序?
用于将输出发送到另一个文件(我省略了错误判断,将重点放在重要的细节上):
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(...);
}
用于将输出发送到管道,以便您可以将输出读取到缓冲区中:
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)
{
}
}