1. 程式人生 > 實用技巧 >Linux下多程序程式設計

Linux下多程序程式設計

一、linux下通過程序編號管理程式執行,主要通過fork函式實現多程序程式設計。通過該函式,實現系統呼叫建立一個與原來程序幾乎完全相同的程序,兩個程序幾乎可以完成一模一樣的事情,通過初始引數的不同,實現不同的功能。主要通過返回值的不同區分進行型別, 返回0表示是子程序,如果是非0,則是建立的程序的id。

  呼叫的格式為:

 1 int  mypid;
 2 mypid = fork();
 3 if(mypid < 0){
 4     //建立程序失敗,也許是記憶體不足,也許是程序總數不足
 5 }else{
 6    if(mypid == 0){
 7       //子程序程式碼
 8    }else
{ 9 //父程序程式碼 10 } 11 }

二、模擬shell終端,程式碼(test7_1.c)

 1 //This is c program code!                                                                                                                                                                   
 2 /* *=+=+=+=+* *** *=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
 3   * 文件資訊: *** :~/test7_1.c
 4   * 版權宣告: *** :(魎魍魅魑)MIT
 5   * 聯絡信箱: *** :[email protected]
 6   * 建立時間: *** :2020年11月15日的下午06:35
 7   * 文件用途: *** :資料結構與演算法分析-c語言描述
 8   * 作者資訊: *** :guochaoxxl(
http://cnblogs.com/guochaoxxl) 9 * 修訂時間: *** :2020年第45周 11月15日 星期日 下午06:35 (第320天) 10 * 檔案描述: *** :自行新增 11 * *+=+=+=+=* *** *+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+*/ 12 #include <stdio.h> 13 #include <sys/wait.h> 14 #define MAXLINE 100 15 16 int main(int argc, char **argv)
17 { 18 int pid; 19 int jg; 20 int status; 21 int len; 22 char buf[MAXLINE]; 23 24 printf("\n##myshell~~"); 25 while(fgets(buf, MAXLINE, stdin) != NULL){ 26 len = strlen(buf) - 1; 27 if(buf[len] == '\n'){ 28 buf[len] = 0; 29 } 30 pid = fork(); 31 if(pid < 0){ 32 printf("fork error!\n"); 33 }else{ 34 if(pid == 0){ 35 printf("\n"); 36 if(buf[0] == 'Q' && strlen(buf) == 1){ 37 exit(200); 38 } 39 jg = execlp(buf, buf, (char *)0); 40 if(jg == -1){ 41 printf("不能執行: %s\n", buf); 42 exit(127); 43 } 44 exit(0); 45 }else{ 46 if((jg == waitpid(pid, &status, 0)) < 0){ 47 printf("waitpid error\n"); 48 } 49 if(WEXITSTATUS(status) == 200){ 50 printf("退出。。。\n"); 51 break; 52 } 53 } 54 } 55 exit(0); 56 } 57 58 return 0; 59 }

  程式碼比較簡單不再囉嗦