操作系统:Linux,语言:纯C
我正在学习一般的C编程,以及在特殊情况下在UNIX下进行C编程.
printf()在使用fork()呼叫后,我发现了一个奇怪的(对我来说)函数的行为.
码
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf( "Hello, my pid is %d", getpid() );
pid = fork();
if( pid == 0 )
{
printf( "\nI was forked! :D" );
sleep( 3 );
}
else
{
waitpid( pid, NULL, 0 );
printf( "\n%d was forked!", pid );
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
产量
Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!
Run Code Online (Sandbox Code Playgroud)
为什么第二个"Hello"字符串出现在子输出中?
是的,这正是父母在开始时与父母一起打印的内容pid …
fork()创建一个新进程,子进程从父进程的当前状态开始执行.
这是我fork()在Linux中所知道的.
所以,相应的代码如下:
int main() {
printf("Hi");
fork();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
需要按照上述方式仅打印一次"Hi".
但是在使用gcc编译的Linux中执行上述操作时,它会打印两次 "Hi" .
有人可以向我解释实际使用中发生了什么,fork()以及我是否理解了fork()正确的工作?
可能重复:
在linux gcc中使用fork()
#include <stdio.h>
void main ()
{
printf ("ciao");
fork ();
}
Run Code Online (Sandbox Code Playgroud)
我有一些关于C优化的想法,但我不确定.希望你知道答案.
有2个不同的程序,它们很小,例如:
int main()
{
printf ("print hello");
fork();
}
Run Code Online (Sandbox Code Playgroud)
int main()
{
printf ("print hello\n");
fork();
}
Run Code Online (Sandbox Code Playgroud)
输出1是:`print helloprint hello
输出2是:print hello
问题是,为什么\n只打印一次,第一次打印两次?