fork函数注意的几点

#include 
#include 
#include 
#include 

// file operations the character\line\block functions contain the stream in the end.other not.
int main()
{
	int num = 0;
	pid_t pid;
	printf("excute begin!\n");
	printf("processid:%d\n",getpid());
	if((pid = fork()) < 0){
		//fprintf("%s","error fork\n",stderr);
		fprintf(stderr,"%s","error fork!\n");
		exit(EXIT_FAILURE);
	}else if(pid == 0){// child process
		num ++;
	}else{
		sleep(2);
	}
	printf("the num of process %d is %d,it's parent process is %d\n",getpid(),num,getppid());
	return 0;
}

上面这个程序是用于测试fork()函数是否会从头开始的,实验结果是不会:

huangkq@huangkq-Lenovo-G450:~/Desktop/Algorithms$ ./head 
excute begin!
processid:2904
the num of process 2905 is 1,it's parent process is 2904
the num of process 2904 is 0,it's parent process is 2291

但当使用了重定向时,前面的会输出两次呢?如下:

huangkq@huangkq-Lenovo-G450:~/Desktop/Algorithms$ cat tmp.out 

excute begin!
processid:2909
the num of process 2910 is 1,it's parent process is 2909
excute begin!
processid:2909
the num of process 2909 is 0,it's parent process is 2291

这主要是缓冲区的问题,在交互式方式下运行该程序,即第一种,它是行缓冲,标准输出缓存区由换行符冲洗掉了。

而下面的重定向则在fork时,该数据还在缓存区,然后全被复制到子进程中,于是父子进程都有了。

但我们可以注意到processid都是2909,也就是说子进程不会重头开始执行。

你可能感兴趣的:(Linux开发,character,include,stream,file,测试)