歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

Linux進程控制實驗

一. 實驗目的
1.掌握Linux創建進程。
2.掌握Linux父子進程同步。
3.掌握Linux子進程的重新加載。
4.進一步熟悉linux下vi的使用和C源程序的編譯與運行。

二. 實驗准備
1. 創建子進程函數:
fork()
說明:返回值   0  創建成功,從子進程返回
    >0創建成功,從父進程返回,其值為子進程的PID號
    -1創建失敗
2. 進程終止函數:
 exit(int status)
說明:是一個不返回函數,所用頭文件#include<stdlib.h>
3. 父進程等待子進程終止函數:
 (1)wait()
 (2)waitpid()
 說明:頭文件#include<sys/wait.h>
    #include<sys/types.h>
   返回值:≥0 表示有子進程終止,其值為終止子進程的pid號
    -1   表示無子進程終止
三.實驗內容
編譯實驗,分析運行結果
1、 程序1(test1.c):要求畫出進程家族樹
#include <stdio.h>
int main(void)
{
    fork ( );
  fork ( );
  fork ( );
  putchar( ‘A’ );   
   }

2、 程序2(test2.c)
#include <stdio.h>
int main(void)
{
    int p1;
  putchar(‘x’);
  while((p=fork())= =-1);
if(p1= =0)
 putchar(‘b’);
  else
   putchar(‘a’);
   
  putchar(‘y’);
 }

3、 程序3(test3.c)
#include <stdio.h>
int main(void)
{
    int p1;
  putchar(‘x’);
  while((p=fork())= =-1);
if(p1= =0)
{
 putchar(‘b’);
 exit(0);
}
  else
   putchar(‘a’);
   
  putchar(‘y’);
 }

4、 程序4(test4.c)
#include <stdio.h>
int main(void)
{
    int p1;
  int x=1;
  while((p=fork())= =-1);
if(p1= =0)
{
 putchar(‘b’);
x=9;
   printf(“%d”,x);
    }
  else
  {
   putchar(‘a’);
   printf(“%d”,x);
  }
   }

5、 程序5(test5.c)
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
    int p1;
  while((p=fork())= =-1);
if(p1>0)
{
 wait(0);
 putchar(‘b’);
}
  Else
  {
   putchar(‘a’);
   exit(0);
  }  
 }

6、 
(1)子進程程序(chld.c)
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
main(  )
{
   Printf(“I am child\n”);
 Exit(0);
}

(2)父進程程序(test6.c)
#include <unistd.h>
#include <stdio.h>
int main()
{
Int p
While((p=fork())= = -1);
If(p= =0)
 Execl(“./chid”,0);
Else
{
 Wait(0);
 Exit(0);
}
}
四.實驗報告
實驗課題、目的與主要內容要求,實際進行的實驗詳細記錄及每一個實驗階段環節的分析與結論。

Copyright © Linux教程網 All Rights Reserved