c - GNU time 实用程序如何忽略管道符号并将命令行中剩下的所有内容作为一个 execve 参数?

标签 c linux time pipe gnu

Linux,如果我运行 time tar -c stock_file | lz4 > stock_file.lz4,实际上它生成类似 time (tar -c stock_file | lz4 > stock_file.lz4) 的东西,但如果我编写一个小程序:

#include <stdio.h>

int main (int argc, char **argv)
{
    for (int i = 1; i < argc; ++i)
    {
        printf("The %dth user parameter, %s\n", i, argv[1]);
    }
    return 0;
}

然后我将它构建到 pretending_time 并运行它:

shell@kernel: ~> ./pretending_time well | cat
The 1th user parameter, well

嗯嗯,参数是well不是well | cat,然后我检查了 time 的源代码来弄清楚 time 如何使用 well | cat 作为一个参数

git clone git://git.savannah.gnu.org/time.git

只有一个文件源码,感觉不错

int
main (argc, argv)
     int argc;
     char **argv;
{
  const char **command_line;
  RESUSE res;

  ......
}

感觉不好,仔细编译

error: ‘argc’ was not declared in this scope
error: ‘argv’ was not declared in this scope
error: initializer expression list treated as compound expression
error: expected ‘,’ or ‘;’ before ‘int’
error: expected unqualified-id before ‘{’ token

什么是

int
main (argc, argv)
     int argc;
     char **argv;
{

没见过,编译不了,c-lang允许这样吗? time 参数中的管道符号 | 是这样吗?

疑惑解决后编辑

在我的 shell 中有一个内置命令 time,但是 which 会找到独立的 time 实用程序,如果有内置命令,你可以

shell@kernel: ~> help | grep -Eo "\btime .*"
time [-p] pipeline

最佳答案

time 的行为与其他(外部)程序不同的原因是 time 实际上不是程序,它是 bash 内置的。为了进行比较,请考虑以下示例:使用 bash 内置我们得到

$ time sleep 1 | sleep 2
real   0m2.003s

而对于外部时间

$ /usr/bin/time sleep 1 | sleep 2
0.00user 0.00system 0:01.00elapsed 0%CPU (0avgtext+0avgdata 7488maxresident)k

如您所见,在第一种情况下,time 乘以两个 sleep 操作,而在第二种情况下,它仅乘以第一个 sleep .一般来说,不可能将 time 构建为像第一个示例那样工作的外部程序。原因是每当 bash 看到管道字符时,它会独立执行左边的东西和右边的东西。所以左边永远没有机会看到右边命令的样子。另一方面,通过内置的 time,bash 可以识别它并对其进行特殊处理。

关于c - GNU time 实用程序如何忽略管道符号并将命令行中剩下的所有内容作为一个 execve 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39629246/

相关文章:

c - 使用指针作为动态分配的数组

c - 简单加密 - C 中的哈希总和

linux - 如何在每次 grep 找到某些东西时增加变量的值

c - FIFO 上的多个读取器/写入器(命名管道)

Golang fmt.Println 定时器

c++ - 为什么 C/C++ 静态库以 '.a' 结尾?

css - 闪烁的按钮(带有 GTK+ 的 C)

linux - Python 找不到 mongoengine 模块

php - 按时间和日期过滤

java - 比较java中的时间