简体   繁体   English

c-使用提示符实现shell:子级在父waitpid之后打印

[英]c - implementing a shell with prompt : child prints after parent waitpid

I'm currently trying to implement a basic shell programm which wait for user to prompt a single command (just like "ls" or something else) and this following code is working, except that I get a weird output... 我目前正在尝试实现一个基本的shell程序,该程序等待用户提示单个命令(就像“ ls”或其他命令一样),并且下面的代码正在工作,除了得到奇怪的输出...

Code

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <errno.h>


char *username;
char hostname[1024];
char currentdir[1024];
char shell_input[256];
int error_code;

int main() {

    int pid, status;
    char *pos;
    username = getenv("USER");
    gethostname(hostname, sizeof(hostname));
    getcwd(currentdir, sizeof(currentdir));

    while(1){
        printf("%s@%s:%s$ ", username, hostname, currentdir);
        fgets(shell_input, sizeof(shell_input), stdin);

        // deleting the newline captured by fgets
        if ((pos=strchr(shell_input, '\n')) != NULL)
            *pos = '\0';

        if((pid = fork())==0){
            error_code= execlp(shell_input, shell_input, NULL);
            if(error_code!=0){
                printf(" %s \n", strerror(errno));
                exit(0);
            }
        }else{
            waitpid(pid, &status, -1);
        }
    }
}

As expected, when i run my program, i'v got this console prompt : 不出所料,当我运行程序时,我得到了以下控制台提示:

jeremy@jeremy-pc:/home/jeremy/Cours$ 

Then, if want to run the ls command in my program, the command works but i got this output : 然后,如果要在我的程序中运行ls命令,该命令有效,但我得到了以下输出:

jeremy@jeremy-pc:/home/jeremy/Cours$ ls
jeremy@jeremy-pc:/home/jeremy/Cours$ example    prototype.c      dir1    prototype

The problem here, is that the "prompt" string (jeremy@jeremy-pc etc...) is printed before the ls result which is supposed to be printed before the waitpid. 这里的问题是,“提示”字符串(jeremy @ jeremy-pc等)在ls结果之前打印,该结果应该在waitpid之前打印。

So my question is, what's wrong in my code as long as i don't get a result like this : 所以我的问题是,只要我没有得到这样的结果,代码中有什么问题:

jeremy@jeremy-pc:/home/jeremy/Cours$ ls
example    prototype.c       dir1    prototype
jeremy@jeremy-pc:/home/jeremy/Cours$ 

Thank you in advance for your help and for your time, have a good day :) 预先感谢您的帮助和时间,祝您有个美好的一天:)

You have a problem with the option argument of waitpid . 您对waitpidoption参数有waitpid By giving -1 (0xFFFFFFFF) as third argument, you probably enable all options including WNOHANG , which is described as return immediately if no child has exited. 通过将-1(0xFFFFFFFF)作为第三个参数,您可能会启用所有选项,包括WNOHANGreturn immediately if no child has exited.其描述为return immediately if no child has exited. in manpage. 在联机帮助页中。

Disabling all flags would make waitpid wait for process to exit: 禁用所有标志将使waitpid等待进程退出:

waitpid(pid, &status, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM