QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1442|回复: 7

有关fork

[复制链接]
发表于 2003-11-1 22:26:38 | 显示全部楼层 |阅读模式
对不住啊斑竹,可我真的找不到合适的地方来提这个简单的问题。

是关于fork调用的。下面这段程序:

#include<stdio.h>
#include<sched.h>

void main()
{   
     putchar('a');
     fork();
     printf("bye\n");
}

运行结果:
abye
abye
为什么会输出两遍 a ?这是不是说明在调用fork生成子进程时,子进程要从头开始再执行一遍?(老师就是这样教的)
但很多书上说,创建后不管对于子进程和父进程,控制都是返回到fork下一条代码的呀。
另外,如果在fork前的标准输出语句中有 "\n" 的话,就只输出一遍,这又是为什么?
有哪为好心人能详细讲一下,fork 对于子进程到底是什么流程啊?
发表于 2003-11-1 23:30:48 | 显示全部楼层
u have two id? why does 'mp3' ask the same question?

homework?

this is the wrong place to ask this question, (you already know).

[code:1]
#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
}
}
[/code:1]

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.
回复

使用道具 举报

 楼主| 发表于 2003-11-2 17:39:32 | 显示全部楼层
but what is glibc? does child must print contents of buffered i/o?is that a kink of  initialization 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
回复

使用道具 举报

发表于 2003-11-2 20:56:18 | 显示全部楼层
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.
回复

使用道具 举报

发表于 2003-11-2 20:57:28 | 显示全部楼层
sorry for my poor english  :-(
回复

使用道具 举报

发表于 2003-11-3 10:57:34 | 显示全部楼层
[quote:c6b9449737="_z_"]sorry for my poor english  :-([/quote]

i can understand what u to say.    but i do not think everybody should use english here. i think u can use what you want.    
回复

使用道具 举报

发表于 2003-11-3 10:59:53 | 显示全部楼层
[quote:c8091e324f="yuchuan"]but what is glibc? does child must print contents of buffered i/o?is that a kink of  initialization 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[/quote]

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
回复

使用道具 举报

 楼主| 发表于 2003-11-3 16:59:22 | 显示全部楼层
i get it.thx for all of you.i like here very much.
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-11-16 07:50 , Processed in 0.074128 second(s), 15 queries .

© 2021 Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表