OS实验六:进程控制

实验六:进程控制

实验目的

  1. 巩固进程创建的知识
  2. 掌握wait()sleep()等调用的功能及基本的使用方法。
  3. 了解exec()系统调用的基本知识

实验内容

  1. 用fork( )创建一个进程,再调用exec( )用新的程序替换该子进程的内容
  2. 利用wait( )来控制进程执行顺序
  3. 使用sleep()系统调用,让子进程“睡眠”10秒钟

实验资料: 

  1. exec( )系列

   在Linux中,并不存在一个exec()的函数形式,exec指的是一组函数,一共有6个,分别是:
  
  #include
  int execl(const char *path, const char *arg, ...);
  int execlp(const char *file, const char *arg, ...);
  int execle(const char *path, const char *arg, ..., char *const envp[]);
  int execv(const char *path, char *const argv[]);
  int execvp(const char *file, char *const argv[]);
  int execve(const char *path, char *const argv[], char *const envp[]);

exec函数族的作用是根据指定的文件名找到可执行文件,并用它来取代调用进程的内容,换句话说,就是在调用进程内部执行一个可执行文件。

  1. wait()系统调用:

原型:

#include<sys/types.h>

#include<sys/wait.h>

Pid_t wait(int *status)

等待子进程运行结束。如果子进程没有完成,父进程一直等待。wait( )将调用进程挂起,直至其子进程因暂停或终止而发来软中断信号为止。

参数可以是NULL此时父进程对于这个子进程是如何死掉的不关心,仅仅是想把子进程彻底的消灭掉。

  1. sleep()函数调用

原型:#include<unistd.h>

Unsigned int sleep(unsigned int seconds)

该函数调用使进程挂起指定的数。

  1. exit()

终止进程的执行。

系统调用格式:

    void exit(status)

       int status;

为了及时回收进程所占用的资源并减少父进程的干预,利用exit( )来实现进程的自我终止,通常父进程在创建子进程时,应在进程的末尾安排一条exit( ),使子进程自我终止。exit(0)表示进程正常终止,exit(1)表示进程运行有错,异常终止。

参考程序

1.

#include<stdio.h>
#include<unistd.h>
main( )
{      
        int pid;    
        pid=fork( );         /*创建子进程*/
switch(pid) 
{
               case  -1:                          /*创建失败*/
                       printf("fork fail!\n");
                       exit(1);
               case  0:                                 /*创建了一个子进程*/
                       execl("/bin/ls","ls","-1","-color",NULL);  
                       printf("exec fail!\n");
                       exit(1);
               default:                                 /*父进程*/
                       wait(NULL);                  /*同步*/
                       printf("ls completed !\n");
                       exit(0);
          }
}

运行结果

执行命令ls  -l  -color ,(按倒序)列出当前目录下所有文件和子目录;

ls completed!

分析原因

程序在调用fork( )建立一个子进程后,马上调用wait( ),使父进程在子进程结束之前,一直处于睡眠状态。子进程用exec( )装入命令ls ,exec( )后,子进程的代码被ls的代码取代,这时子进程的PC指向ls的第1条语句,开始执行ls的命令代码。

2.

#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
main()
{
pid_t  pc,pr;
pc=fork();
if(pc<0)
printf(“creat error\n”);
else  if(pc==0){
printf(“this is child process with pid of %d\n”,getpid());
sleep(10);
}
else{
pr=wait(NULL);
printf(“I catch a child process with pid of%d\n”,pr);
}
exit(0);
}

猜你喜欢

转载自blog.csdn.net/qq_50777680/article/details/121127524