![](/img/trans.png)
[英]Why I don't have to flush the output buffer while using printf everytime?
[英]execlp fails if I don't flush the buffer
我正在尝试在 C 中的子进程中运行命令:
int main()
{
if (fork()) {
wait(0);
} else {
fflush(stdout);
execlp("ls", "ls");
printf("Command not found: \"%s\"\n", "ls");
}
}
我的理解是对fork()
的调用将创建进程(子进程fork()
的克隆。 这里的父进程将wait(0)
,因为fork()
不返回 null,并等待子进程完成。
我理解子进程的图像在调用execlp("ls", "ls");
之后基本上“变成”了ls
execlp("ls", "ls");
.
此时,如果ls
存在于路径中,则ls
程序将接管并且永远不应调用第 8 行的printf()
。
这与我上面发布的代码段的预期工作一样,并且我在当前目录中获得了ls
的输出。
但是,如果我注释掉fflush(stdout)
, printf()
就会被调用!
Command not found: "ls"
如果我注释掉fflush(stdout)
为什么会调用printf()
fflush(stdout)
?
以下建议代码:
stderr
execlp()
main()
函数fork()
返回的值做出假设现在,建议的代码:
#include <stdio.h> // perror(), printf()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <unistd.h> // execlp(), fork(), pid_t
#include <sys/wait.h> // wait()
int main( void )
{
pid_t pid = fork();
if ( pid < 0 )
{ // then error
perror( "fork failed" );
exit( EXIT_FAILURE );
}
if( pid == 0 )
{ // then child
execlp("ls", "ls", NULL );
perror( "execlp failed" );
exit( EXIT_FAILURE );
}
else
{ // then parent
wait(0);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.