sx6701829 发表于 2013-04-11 19:17

linux 父子进程代码执行

我主要想知道代码中父子进程分别如何执行的,我自己写了一段小代码


#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{    -----------------------------------1
FILE * fp=NULL;
int fd,t,i=10;
char buf="i love you";

fp=fopen("./b.c","a+");
if(fp == NULL)
printf("open wrong\n");


if (fwrite(buf,1,15,fp) == 0)
printf("write error\n");


printf("ok\n");

---------------------------------------2
if((t=fork()) >0 )

printf("farther\n");
--------------------------------------3
else if (t == 0)
{
printf("son\n");

fwrite(buf,1,15,fp);
-------------------------------------4
}
return 0;
}
输出:
ok
son
farther

打开b.c
i love you i love you i love you

按照输出的结果推算1~2段执行一次,写了一次在子进程3~4段也写了一次可是结果写了三次,这个执行顺序是什么样的啊?????
请指教????

sx6701829 发表于 2013-04-11 20:03

自己顶个:'(:'(:'(:'(:'(:'(:'(

to407 发表于 2013-04-12 11:04

回复 1# sx6701829


    在2上面, printf("ok\n"); 上加一句fflush(fp);如果不做flush的话,缓冲还没有实际完成写, 会在fork里被继承给子进程。

sx6701829 发表于 2013-04-12 16:11

to407 发表于 2013-04-12 11:04 static/image/common/back.gif
回复 1# sx6701829





谢谢,完全正确!!1
页: [1]
查看完整版本: linux 父子进程代码执行