关于fork()函数特性的一些探究

fork()函数用于产生一个子进程,和当前的进程并行执行。通过判断fork函数的返回值可以区分是父进程还是子进程,如果返回为0,则为子进程。

对于fork函数的执行方式,自己还是存在一些不明,写了一个简单的测试程序测试fork函数的一些性质。

测试程序如下:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
	pid_t pid;
	int test = 3;
	FILE* fp;

	fp = fopen("test.txt", "w");

	printf("This is the start!\n");

	if ((pid = fork()) == 0)
	{
		fprintf(fp, "child\n");
		printf("This is the child process.\n");
		printf("child: test = %d\n", test);
		fclose(fp);
	}
	else
	{
		fprintf(fp, "parent\n");
		test = 200;
		printf("This is the parent process.\n");
		printf("parent: test = %d\n", test);
		fclose(fp);
	}

	return 0;
}
执行的结果为:

This is the start!
This is the parent process.
parent: test = 200
This is the child process.
child: test = 3
生成的test.txt文件的内容为:

parent
child

分析:

首先,This is the start. 这句只在屏幕上输出一次。因此fork函数创建的子进程没有从头开始执行,而是从当前开始执行的。

其次,关于变量test的值,可以看到,子进程的变量与父进程变量的值是一样的,但是没有共享。因为父进程改变了局部变量的值,并没有影响到子进程。

最后,关于test.txt文件的内容。该文件没有只显示parent或者child,因此两个进程中的fclose函数必有一个没有关闭文件。而是两个都关闭后,文件才真正的关闭。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章