我正在写一个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)
    {
    }
}

C++相关问答推荐

有什么方法可以从Linux中未剥离的二进制文件中取回源代码吗?

问关于C中的指针和数组

GCC:try 使用—WError或—pedantic using pragmas

什么C代码将确定打开的套接字正在使用的网络适配器?

如何在C宏中确定Windows主目录?

使用额外的公共参数自定义printf

Win32API Wizzard97 PropSheet_SetWizButton不工作

将数组插入数组

为什么realloc函数在此代码中修改变量?

GCC错误,共享内存未定义引用?

如何在VSCode中创建和使用我自己的C库?

将 struct 数组写入二进制文件时发生Valgrind错误

隐藏测试用例无法在c程序中计算位数.

与外部SPI闪存通信时是否应禁用中断?

为什么GCC 13没有显示正确的二进制表示法?

在git补丁中自动添加C的宏

I';我试着从.txt文件中读取文本,并用c计算其中的单词数量

在分配内存后使用指针是未定义的行为吗?

在C中定义函数指针?

在 C 中的 scanf() 格式说明符中使用宏获取字符串长度