c++ - 为什么我的程序在 Linux 上运行时 splice syscall 失败,而在 gdb 中运行时成功?

标签 c++ c gdb

我尝试运行一本书的示例代码。它的功能是接受一行输入并将其输出到标准输出和操作参数指定的文件中。
这是代码:

#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>

int main( int argc, char* argv[] )
{
    if ( argc != 2 )
    {
        printf( "usage: %s <file>\n", argv[0] );
        return 1;
    }
    int filefd = open( argv[1], O_CREAT | O_WRONLY | O_TRUNC, 0666 );
    assert( filefd > 0 );

    int pipefd_stdout[2];
        int ret = pipe( pipefd_stdout );
    assert( ret != -1 );

    int pipefd_file[2];
        ret = pipe( pipefd_file );
    assert( ret != -1 );

    //the first splice()
    ret = splice( STDIN_FILENO, NULL, pipefd_stdout[1], NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE );
    assert( ret != -1 );

    ret = tee( pipefd_stdout[0], pipefd_file[1], 32768, SPLICE_F_NONBLOCK ); 
    assert( ret != -1 );

    //the second splice()       
    ret = splice( pipefd_file[0], NULL, filefd, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE );
    assert( ret != -1 );

    //the third splice()
    ret = splice( pipefd_stdout[0], NULL, STDOUT_FILENO, NULL, 32768, SPLICE_F_MORE | SPLICE_F_MOVE );
    printf("errno:%d\n",errno);
    assert( ret != -1 );


    close( filefd );
        close( pipefd_stdout[0] );
        close( pipefd_stdout[1] );
        close( pipefd_file[0] );
        close( pipefd_file[1] );
    return 0;
}
编译代码后,我运行它并输入“123”,它无法输出到标准输出,第三个 splice() 失败并且 errno 为 22。这是结果的屏幕截图:
p1
当我使用 gdb 运行代码时,它可以正常工作。这是截图:
p2
内核版本:4.19.163-1
gcc 版本:10.2.0
gdb 版本:10.1
我的编译命令:g++ test.cpp -g -o LinuxServer
我的运行命令:./LinuxServer test.txt
我的 gdb 命令:gdb LinuxServer
那么为什么我的程序在 Linux 上运行时 splice 系统调用失败,而在 gdb 中运行时成功呢?

最佳答案

在linux手册splice(2)中,有关于ERRORS: EINVAL The target file is open in append mode的说明。
我终端中的标准输出处于追加模式,这就是第三个拼接系统调用失败的原因。
为了解决这个问题,我们可以添加 fcntl(STDOUT_FILENO, F_SETFL, fcntl(STDOUT_FILENO, F_GETFL) & ~O_APPEND);在拼接系统调用之前。

关于c++ - 为什么我的程序在 Linux 上运行时 splice syscall 失败,而在 gdb 中运行时成功?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65749455/

相关文章:

c++ - 如何避免-fpermissive?

c - 理解在内存地址返回值的 c#define

c - C 中的静态成员

c++ - 如何设置 VSCode C++ 来显示局部变量

c++ - gdb,hp ux : getting message Couldn't find virtual table -- object may not be constructed yet

c++ - C++ 语言标准对 static_cast 如何处理减小整数的大小有何规定?

c++ - 两个排序数组的中位数

c++ - 加载实例时开始 C++ 开发人员 EXC_BAD_ACCESS 错误

c++ - C++ 中 void* 的返回类型

c++ - C/C++ 将字符串放入二维数组?