Execv Linux printf不起作用 [英] Execv Linux printf doesn't work

查看:97
本文介绍了Execv Linux printf不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下C代码运行可执行文件:

I'm trying to run executable using this c code:

  int main(int argc, char *argv[])
  {
     printf("hello.\n");
     sleep(2);
     if (execlp("ls","ls","-l",NULL) == -1)
          printf("Error occured during execute ls.\n");
     return 0;
 }

为什么使用printf("hello \ n") 不起作用?即使我睡觉了?

why printf("hello\n") doesn't work? even if i put sleep?

推荐答案

当输出到终端时,您的程序应该可以运行,但是如果将输出重定向到文件或管道,则该程序将无法正常工作.当stdout未连接到端子时,其输出将被完全缓冲.在使用新程序替换当前进程之前,调用exec函数不会刷新缓冲区,因此任何缓冲的输出都将丢失.

Your program should work when output is to a terminal, but it will not work correctly if output is redirected to a file or a pipe. When stdout is not connected to a terminal, its output is fully buffered. Calling an exec function does not flush the buffer before replacing the current process with the new program, so any buffered output will be lost.

在调用execlp()之前先调用fflush(stdout);,该问题应得到解决.您不需要睡觉,对输出没有影响.

Call fflush(stdout); before calling execlp() and the problem should be resolved. You don't need to sleep, it has no effect on output.

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])
  {
     printf("hello.\n");
     fflush(stdout);
     if (execlp("ls","ls","-l",NULL) == -1)
          printf("Error occured during execute ls.\n");
     return 0;
 }

这篇关于Execv Linux printf不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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