實驗目的
1、理解
fork
系統調用工作原理,使用fork
創建子進程
2、理解execve
系統調用工作原理,使用execve
加載執行新程
3、調試跟蹤fork
和execve
系統調用函數的執行過程實驗內容
實驗要求
主程序在創建子進程後要等待子程序執行結束纔打印PID號,最後結束運
行。
程序準備
由實驗內容知道,需要寫三個程序,分別是lab3、leap、info。新建三個源文件。
#include <stdio.h>
int main( int argc, char** argv ) {
printf( "Class:%s\n", "software 501" );
printf( "Student ID:%s\n", "173401050117" );
printf( "Student name:%s\n", "Liao Jie" );
return 0;
}
info的用於輸出學生信息,根據情況自行修改。
#include <stdio.h>
int main( int argc, char** argv ) {
int year = -1;
printf( "Please Enter Year:" );
fflush( stdout ); //清除緩存區
scanf( "%d", &year );
if( year%400 == 0 || year%100!=0 && year%4==0 )
printf( "%d is leap year\n", year );
else
printf( "%d is not leap year\n", year );
return 0;
}
fflush
的作用詳見百科-fflush,不這樣做的話,printf的內容會在scanf輸入之後輸出,因爲在scanf輸入之前,字符串被放入了緩存區內。經驗來自C/C++執行scanf優先於printf。leap用於判斷平閏年。
#define __LIBRARY__
#include <stdio.h>
#include <unistd.h>
int main( int argc, char** argv ) {
int choice = -1, pid = -1;
printf("1.student infomation\n2.Leap Year\n3.Exit\nplease enter your choice:\n");
while( 1 ) {
scanf("%d", &choice);
if( choice%3 > 2 || choice <= 0 ) return -1;
else {
switch( choice ) {
case 1:
pid = fork();
if( pid < 0 ) return -1;
if( pid ) {
printf("NO.1 child process:PID=%d\n", pid);
waitpid( pid, NULL, 0 );
printf("Parent process:PID=%d\n", getpid());
}
else {
execve( "info", NULL, NULL );
}
break;
case 2:
pid = fork();
if( pid < 0 ) return -1;
if( pid ) {
printf("NO.2 child process:PID=%d\n", pid);
waitpid( pid, NULL, 0 );
printf("Parent process:PID=%d\n", getpid());
}
else {
execve( "leap", NULL, NULL );
}
break;
case 3:
return 0;
break;
}
}
printf( "please enter your choice:\n" );
}
}
lab3是主程序,知識點主要包含這幾個函數:fork、execve、wait、waitpid。
步驟
-
創建Linux011 Kernel項目,打開
FloppyImageEditor
,使用它是爲了將windows上的文件傳輸到Linux磁盤 -
打開項目目錄下的軟盤b
-
把寫好的三個源文件添加進去,保存
-
回到linuxlab F5調試 用mcopy將源文件copy到Linux磁盤
將軟盤b中的文件拷貝到當前目錄
-
分別編譯,加執行權限