2016计算机基地-倪纯淳-实验五.docxVIP

  • 13
  • 0
  • 约2.79千字
  • 约 10页
  • 2018-06-29 发布于上海
  • 举报
实验五2016级计算机基地 倪纯淳阅读下列程序:/* usage of kill,signal,wait */#includeunistd.h#includestdio.h#includesys/types.h#includesignal.h#includestdlib.hint flag;void stop();int main(void){int pid1,pid2;signal(3,stop);while((pid1=fork()) ==-1);if(pid10){while((pid2=fork()) ==-1);if(pid20){flag=1;sleep(5);kill(pid1,16);kill(pid2,17);wait(0);wait(0);printf(“\n parent is killed\n”);exit(EXIT_SUCCESS);}else{flag=1;signal(17,stop);printf(“\n child2 is killed by parent\n”);exit(EXIT_SUCCESS);}}else{flag=1;signal(16,stop);printf(“\n child1 is killed by parent\n”);exit(EXIT_SUCCESS);}}void stop(){flag = 0;}编译并运行,等待或者按^C,分别观察执行结果并分析,注释程序主要语句。flag有什么作用?通过实验说明。每个进程(父进程,子进程)都有一个flag,起状态标志作用,flag=1时,表示进程在运行,flag=0,表示进程结束。编写程序,要求父进程创建一个子进程,使父进程和个子进程各自在屏幕上输出一些信息,但父进程的信息总在子进程的信息之后出现。(通过一个程序实现)代码如下#includeunistd.h#includestdio.h#includestdlib.hmain(){int p,i;while((p=fork())==-1);//创建子进程直至成功if(p0){ wait(0); printf(***\n);printf(The parent process!\n);printf(***\n); exit(0);}else{ printf(***\n);printf(The child process!\n); printf(***\n);sleep(3); exit(0);}}编写程序,要求父进程创建一个子进程,子进程执行shell命令find / -name hda* 的功能,子进程结束时由父进程打印子进程结束的信息。执行中父进程改变子进程的优先级。代码如下:#includestdio.h#includestring.h#includestdlib.h#includeunistd.h#includefcntl.h#includeerrno.h#includesys/resource.hmain(){pid_t pid;int status;pid=fork();if(pid0){//在父进程中设置子进程优先级setpriority(PRIO_PROCESS,pid,15);//输出修改后的子进程的优先级printf(the priority of son process is %d\n,getpriority(PRIO_PROCESS,pid));}//子进程执行代码else{ execlp(find, find, /, -name, hda*, (char *)0); exit(127);}/*使用waitpid()阻塞等待子进程结束,防止父进程过早的退出。子进程终止后,waitpid()返回返回后,可以打印子进程已经终止的信息。*/if ( (pid = waitpid(pid, status, 0)) == -1) { fprintf(stderr, [parent] waitpid error: %s\n, strerror(errno)); exit(-1); } fprintf(stdout, child[%d] terminated\n, pid); exit(0);}编写程序,要求父进程创建一个子进程,子进程对一个50*50的字符数组赋值,由父进程改变子进程的优先级,观察不同优先级进程使用CPU的时间。代码如下:#includestdio.h#includestdlib.h#includeunistd.h#includesys/times.h#includetime.h#includesys/resource.hvoid time_print(char *str,clock_t time){long tps=sysconf(_SC_CL

文档评论(0)

1亿VIP精品文档

相关文档