重定向问题在bash C程序的输出 [英] Problem redirecting a C program output in bash

查看:157
本文介绍了重定向问题在bash C程序的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有codeD在C程序,用printf将消息发送到标准输出和我有麻烦的输出重定向到一个文件(从bash中运行)。

我试过:

  ./程序参数>> program.out
./program参数> program.out
./program>> program.out说法
./program> program.out说法

在每一种情况下,在创建文件program.out但它仍然是空的。执行完毕后结尾的文件大小为0。

如果我忽略执行程序时重定向:

  ./程序参数

接着,被送往用printf到标准输出的所有消息都显示在终端。

我对我已经没有问题重定向输出这种方式与其他C程序。
是否有程序本身呢?与参数传递?
应该在哪里寻找这个问题?

关于C程序的一些细节:


  • 它并不从stdin读取任何

  • 它采用BSD互联网域名插座

  • 它使用POSIX线程

  • 它使用的sigaction分配一个特殊处理函数SIGINT信号

  • 它发出大量的换行到stdout(对于那些你想我应该冲)

有些code:

  INT主(INT ARGC,字符** argv的)
{
    的printf(开始执行\\ n);
    做
    {
        / *很多的printf这里的* /
    }而(1);
    / * code从未达到过* /
    了pthread_exit(EXIT_SUCCESS);
}


解决方案

法拉盛换行符后打印到终端的时候,但不一定在打印到文件时才会起作用。快速谷歌搜索显示有进一步的信息,这个网页:<一href=\"http://www.pixelbeat.org/programming/stdio_buffering/\">http://www.pixelbeat.org/programming/stdio_buffering/

请参阅标题为默认缓冲模式的部分。

您可能需要添加一些调用fflush(标准输出),毕竟。

您还可以通过设置缓冲区的大小和行为 setvbuf用来

I've coded a program in C that sends messages to the stdout using printf and I'm having trouble redirecting the output to a file (running from bash).

I've tried:

./program argument >> program.out
./program argument > program.out
./program >> program.out argument
./program > program.out argument

In each case, the file program.out is created but it remains empty. After the execution ends the file size is 0.

If I omit the redirection when executing the program:

./program argument

Then, all messages sent to stdout using printf are shown in the terminal.

I have other C programs for which I've no problem redirecting the output this way. Does it have to do with the program itself? with the argument passing? Where should look for the problem?

Some details about the C program:

  • It does not read anything from stdin
  • It uses BSD Internet Domain sockets
  • It uses POSIX threads
  • It assigns a special handler function for SIGINT signal using sigaction
  • It sends lots of newlines to stdout (for those of you thinking I should flush)

Some code:

int main(int argc, char** argv)
{
    printf("Execution started\n");
    do
    {        
        /* lots of printf here */
    } while (1);
    /* Code never reached */
    pthread_exit(EXIT_SUCCESS);
}

解决方案

Flushing after newlines only works when printing to a terminal, but not necessarily when printing to a file. A quick Google search revealed this page with further information: http://www.pixelbeat.org/programming/stdio_buffering/

See the section titled "Default Buffering modes".

You might have to add some calls to fflush(stdout), after all.

You could also set the buffer size and behavior using setvbuf.

这篇关于重定向问题在bash C程序的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆