有关fork
对不住啊斑竹,可我真的找不到合适的地方来提这个简单的问题。是关于fork调用的。下面这段程序:
#include<stdio.h>
#include<sched.h>
void main()
{
putchar('a');
fork();
printf("bye\n");
}
运行结果:
abye
abye
为什么会输出两遍 a ?这是不是说明在调用fork生成子进程时,子进程要从头开始再执行一遍?(老师就是这样教的)
但很多书上说,创建后不管对于子进程和父进程,控制都是返回到fork下一条代码的呀。
另外,如果在fork前的标准输出语句中有 "\n" 的话,就只输出一遍,这又是为什么?
有哪为好心人能详细讲一下,fork 对于子进程到底是什么流程啊? u have two id? why does 'mp3' ask the same question?
homework?
this is the wrong place to ask this question, (you already know).
#include<stdio.h>
#include<sched.h>
void main()
{
putchar('a');
if (fork()) {
// parent process will run this code only
}
else
{
// forked child process will run this code only
}
}
check u "man fork" u know why the code is like this.
the reason about the duplicate print out is that linux use buffered i/o. so that print "a' is still in buffer, so this is copied by child process as well. so child process will print thsi out. this is caused by glibc , not kernel.
u can trace the system call by "strace -f ./a.out" to see the system calls it use. but what is glibc? does child must print contents of buffered i/o?is that a kink ofinitialization of child or buffer?
'mp3' is my classmate,and i introduced her here.we are doing linux experiments,so there are lots of difficulties.
i want u email very much.thx glibc is the GNU implementation of c programming language.
both purchar and printf are buffered.
after "fork",child has a copy buffer from his parent.
check some c document. sorry for my poor english:-( sorry for my poor english:-(
i can understand what u to say.:-Dbut i do not think everybody should use english here. i think u can use what you want.:-D:-D but what is glibc? does child must print contents of buffered i/o?is that a kink ofinitialization of child or buffer?
'mp3' is my classmate,and i introduced her here.we are doing linux experiments,so there are lots of difficulties.
i want u email very much.thx
u had better find some document about unix programming to know more. The best is APUE (advanced programming in unix environment). there are chinese version in china, that book is very good.
my email address? mingz(at)ele(dot)uri(dot)edu i get it.thx for all of you.i like here very much.
页:
[1]