计算机操作系统第一次实验——在Linux下创建子进程

用到的函数主要有fork和vfork,fork创建的子进程是对父进程的简单拷贝,它的对资源的修改不会影响父进程;vfrok创建的子进程是父进程的资源共享,此时父进程被阻塞,执行完子进程再执行父进程,子进程对资源的修改会影响父进程。

代码如下(使用的是vfork函数):

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
//创建子进程fork()是简单的拷贝,而vfork()类似于线程,强制执行子进程让父进程阻塞,在子进程执行exit前子进程共享父进程的数据,
//子进程结束后再运行父进程。
int main()
{
	pid_t child;
	int i=0;
	printf("i = %d\n",i);
	char str[50];
	puts("1.excute");
	child = vfork();
	//child = fork();
//无论父子进程都是从fork或vfork后运行的,fork创建了子进程后,在子进程中返回0,在父进程中返回子进程的pid。

	puts("2.excute");
	
	if(child== -1)
	{
		perror("fork");
		puts("fail to create a sup process");
		//exit(1);
	}
	else if(child == 0)
	{
		puts("\nin child:");
		printf("\tchild pid = %d\n",getpid());
		printf("\tchild ppid = %d\n",getppid());
		puts("writing in file :\n This is my work\n");
		FILE  *fp = fopen("123.txt","w");
		fprintf(fp,"%s","This is my work");
		i++;
		printf("i = %d\n",i);
		fclose(fp);
		exit(0);
	}
	else
	{
		waitpid(child,NULL,0);
//等待pid为child的子进程运行,当子进程运行完后父进程运行。
		puts("\nin parent:");
		puts("reading form file ...");
		FILE *fp = fopen("123.txt","r");
		fgets(str,50,fp);
		puts(str);
		fclose(fp);
		i++;
		printf("i = %d\n",i);
		//exit(0);
	}
	return 0;
}

在终端里用gcc编译然后运行,注意,gcc编译后产生的文件main在当前工作目录下。

如图:



当使用fork函数时程序的运行结果如图:


结论:理解概念不能只看书啊,就算简单的创建子进程也要动手写代码,不然永远都是layman(门外汉)!

多写代码多思考,总能使你的理解更深一步。


发布了47 篇原创文章 · 获赞 28 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_41122796/article/details/80259626
今日推荐