簡體   English   中英

為什么execvp()使用fork()執行兩次?

[英]Why is execvp() executing twice using fork()?

我正在實現一個外殼。

當嘗試更改目錄以外的命令時, execvp()運行,該子級終止並創建一個新的子級。 當我更改目錄時,該子級不會終止,並且會創建一個新的子級。 這是我的代碼示例:

for(;;) {
    printf("bash: ");
    parse();
    ...
    pid_t pid = fork()
    if (pid == 0)
        if (!strcmp(line[0], "cd"))
            if (!line[1]) (void) chdir(getenv("HOME"));
            else (void) chdir(line[1]);
        else execvp(line[0], line);
    ...
    if (pid > 0) {
        while (pid == wait(NULL));
        printf("%d terminated.\n", pid);
    }
}

cd ../; ls; 運行正常,除了必須兩次Ctrl+D結束程序。

但是,如果我傳遞相同的信息(即mybash < chdirtest ),則它將正確運行一次,終止子項,直接在原始文件中再次運行,然后終止最終子項。

不應通過子進程調用cd ,shell本身應更改其當前目錄(這是內部命令的屬性:修改shell本身的進程)。

(primitve)shell應該看起來像:

for(;;) {
    printf("bash: ");
    parse();

    // realize internal commands (here "cd")
    if (!strcmp(line[0], "cd")) {
       if (!line[1]) (void) chdir(getenv("HOME"));
       else (void) chdir(line[1]);
       continue; // jump back to read another command
    }

    // realize external commands
    pid_t pid = fork()
    if (pid == 0) {
        execvp(line[0], line);
        exit(EXIT_FAILURE); // wrong exec
    }

    // synchro on child
    if (pid > 0) {
        while (pid == wait(NULL));
        printf("%d terminated.\n", pid);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM