Linux下進程的建立(system(); fork(); exec*())

0. system();html

system()函數經過調用shell程序來執行所指向的命令(效率低),至關於先fork(),再execve();
特色:原進程和子進程各自運行,且原進程須要等子進程運行完後再繼續;
 

1. fork();linux

參考文獻: linux中fork同時建立多個子進程的方法(一)shell

在Linux中用fork()由一個父進程建立同時多個子進程的格式以下:編程

 1 int status,idx;
 2 
 3 for (idx = 0; idx < 10; idx++) {
 4   status = fork();
 5   if (status == 0 || status == -1) break;  // 每次循環時,若是發現是子進程就直接從建立子進程的循環中跳出來,不讓你進入循環,這樣就保證了每次只有父進程來作循環建立子進程的工做
 6 }
 7 
 8 if (status == -1) {
 9   //error
10 } else if (status == 0) {  // 每一個子進程都會執行的代碼
11   //sub process
12 } else {
13   //parent process
14 }

 參考文獻:進程控制:linux中fork同時建立多個子進程注意事項函數

    /* 這裏不能夠一下就建立完子進程,要用 
    *要 建立-》判斷-》使用-》return or exit.更不能這樣如test2.c 
    *childpid1 = fork(); 
    *childpid2 = fork(); 
    *childpid3 = fork(); 
    */  
    childpid1 = fork();                                             //建立  
    if(0 == childpid1)                                              //判斷  
    {                                                               //進入  
        printf("In child1 process\n");  
        printf("\tchild pid = %d\n", getpid());  
        exit(EXIT_SUCCESS);                                         //退出  
    }  

 

2. exec*();學習

參考文獻:spa

linux系統編程之進程(五):exec系列函數.net

Linux下execl學習code

編譯中出現的錯誤:htm

使用execl()函數時出現warning: not enough variables to fit a sentinel

解決方法 - 調整execl中的參數

相關文章
相關標籤/搜索