Linux進程的創建(Linuxlab平臺)

實驗目的

1、理解 fork 系統調用工作原理,使用 fork 創建子進程
2、理解 execve 系統調用工作原理,使用 execve 加載執行新程
3、調試跟蹤 forkexecve 系統調用函數的執行過程

實驗內容

在這裏插入圖片描述在這裏插入圖片描述

實驗要求

主程序在創建子進程後要等待子程序執行結束纔打印PID號,最後結束運
行。


程序準備

由實驗內容知道,需要寫三個程序,分別是lab3、leap、info。新建三個源文件。
在這裏插入圖片描述

  • info.c

#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的用於輸出學生信息,根據情況自行修改。

  • leap.c

#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用於判斷平閏年。

  • lab3.c

#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是主程序,知識點主要包含這幾個函數:forkexecvewaitwaitpid


步驟

  • 創建Linux011 Kernel項目,打開FloppyImageEditor,使用它是爲了將windows上的文件傳輸到Linux磁盤

    在這裏插入圖片描述

  • 打開項目目錄下的軟盤b

    在這裏插入圖片描述

  • 把寫好的三個源文件添加進去,保存

    在這裏插入圖片描述

  • 回到linuxlab F5調試 用mcopy將源文件copy到Linux磁盤

    將軟盤b中的文件拷貝到當前目錄
    在這裏插入圖片描述

  • 分別編譯,加執行權限

    在這裏插入圖片描述


結果

在這裏插入圖片描述


TIPS

  • 一鍵拷貝
    vi創建一個批處理文件in.sh,插入mcopy -n b:leap.c leap.cmcopy b:info.c info.cmcopy -n b:lab3.c lab3.c,然後運行in.sh可以實現一鍵拷貝。(-n 表示若有同名文件不用詢問直接覆蓋)
    在這裏插入圖片描述
    在這裏插入圖片描述
  • 一鍵編譯
    同理,也可以實現一鍵編譯:vi make.sh,插入gcc leap.c -o leapgcc info.c -o infogcc lab3.c -o lab3
    在這裏插入圖片描述
  • vi編輯源文件
    當然,直接在Bochs內寫源文件是可行的,如果可以忍受他的響應時間和vi的編輯習慣的話。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章