linux system 函數的實現源碼

system函數的實現源碼,看到父進程是在子進程執行完成之後才繼續往下走,否則一直掛在那等的子進程執行完。
 

int system(const char * cmdstring)
{
    pid_t pid;
    int status;

    if(cmdstring == NULL){
          
         return (1);
    }


    if((pid = fork())<0){

            status = -1;
    }
    else if(pid == 0){
        execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
        -exit(127); //子進程正常執行則不會執行此語句

        }
    else{
            while(waitpid(pid, &status, 0) < 0){
                if(errno != EINTER){
                    status = -1;
                    break;
                }
            }
        }
        return status;
}

 驗證:

#include <stdio.h>
#include <stdlib.h>
int main(){
        system("sleep 3");
        printf("after system()");
        return 0;
}

 

因此,以上推論是正確的

發佈了13 篇原創文章 · 獲贊 2 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章