Execv Linux printf doesn't work

喜欢而已 提交于 2019-12-02 08:18:49
Barmar

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.

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;
 }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!