首页 > 解决方案 > 使用拼接系统调用没有输出

问题描述

我有以下代码:

#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char **argv) {
  if(argc < 2) {
    fputs("Error: You must provide an filename\n", stderr);
    return 1;
  }

  FILE *handle = fopen(argv[1], "r");
  if(!handle) {
    perror("Error opening file:");
    goto error;
  }

  int handle_fd = fileno(handle);

  int filedes[2];
  if(pipe(filedes)) {
    perror("Error creating pipe:");
    goto error;
  }

  while(1) {
    ssize_t rc = splice(handle_fd, NULL, filedes[1], NULL, BUFSIZ, 0);

    if(rc == -1) {
      // Error occurred
      perror("Error copying data:");
      goto error;
    } else if(rc == 0) {
      break;
    }

    splice(filedes[0], NULL, STDOUT_FILENO, NULL, BUFSIZ, 0);
  }

  return 0;

error:
  if(fclose(handle)) {
    perror("Error closing file:");
  }

  return 1;
}

当我运行它时,我没有得到任何输出。也没有触发任何 perror 调用,我无法弄清楚它为什么不起作用。

当我在 GDB 中运行程序时,它可以工作,但是从 shell 中运行时它不显示任何内容

标签: clinuxsystem-calls

解决方案


您应该检查STDOUT_FILENO是否未在附加模式下打开,否则第二个splice(2)将失败,如其手册页中所述:

EINVAL目标文件以附加模式打开。

是的,即使它是 aa tty 也会发生这种情况,O_APPEND标志不应该有任何区别,这看起来很像一个错误。或者至少是一个麻烦,特别是因为splice不关心O_APPEND标志何时设置在套接字或管道上。

尝试运行您的程序

./your_program file >/dev/tty

或者在你的函数#include <fcntl.h>的开头添加这个:main()

if(isatty(1)) fcntl(1, F_SETFL, fcntl(1, F_GETFL) & ~O_APPEND);

请注意,该O_APPEND标志可能会在您的终端上意外打开:要检查它是否打开,请查看/proc/<pid>/fdinfo/<fd>

$ grep flags /proc/self/fdinfo/1
flags:  0102002
           ^ here it is

O_APPEND一个在其标准输出上打开标志的程序的一个奇怪的例子是GNU make ;-)

$ strace -e trace=fcntl make
fcntl(1, F_GETFL) = 0x48002 (flags O_RDWR|O_LARGEFILE|O_NOATIME)
fcntl(1, F_SETFL, O_RDWR|O_APPEND|O_LARGEFILE|O_NOATIME) = 0
...

一个测试用例,scat.c

/*
 * a simple program which copies its input to its output via splice(2)
 * if given a '1' argument, it will turn the O_APPEND flag on stdout
 * if given a '0' argument, it will turn it off
 * otherwise it will leave it as it is
 */
#define _GNU_SOURCE     1
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <err.h>
int main(int ac, char **av){
        ssize_t z; int fl;
        if(ac > 1){
                if((fl = fcntl(1, F_GETFL)) == -1) err(1, "fcntl(1, getfl)");
                if(atoi(av[1])) fl |= O_APPEND;
                else fl &= ~O_APPEND;
                if(fcntl(1, F_SETFL, fl)) err(1, "fcntl(1, setfl, %x)", fl);
        }
        while((z = splice(0, 0, 1, 0, 65536, 0)))
                if(z < 0) err(1, "splice");
}
$ cc -Wall scat.c -o scat

$ echo yup | ./scat
yup
$ echo yup | ./scat 1
scat: splice: Invalid argument
$ echo yup | ./scat
scat: splice: Invalid argument
$ echo yup | ./scat 0
yup
$ echo yup | ./scat
yup

可以使用管道或套接字作为输出:

$ echo yup | ./scat 1 | cat
yup
$ nc -l -p 9999 &
[4] 23952
$ echo yup | ./scat 1 | nc -q0 localhost 9999
yup
[4]-  Done                    nc -l -p 9999

推荐阅读