簡體   English   中英

Unix C Shell-作業控制問題!

[英]Unix C Shell - Job Control Issue!

我一直在努力用C創建自己的Unix Shell,以實現其互操作性…… 在讓我的Shell繼續接受用戶輸入的同時,我的程序在后台運行時遇到了一些問題 如果您能花時間剖析一下我的不足,將不勝感激!

我的變量在下面,以防萬一,有助於您進一步了解...

#define TRUE 1

static char user_input = '\0'; 

static char *cmd_argv[5]; // array of strings of command
static int cmd_argc = 0; // # words of command

static char buffer[50]; // input line buffer
static int buffer_characters = 0;
int jobs_list_size = 0;

/* int pid; */
int status;
int jobs_list[50];

這是我的主要功能。

int main(int argc, char **argv)
{           
    printf("[MYSHELL] $ ");

    while (TRUE) {
        user_input = getchar();
        switch (user_input) {

            case EOF:
                exit(-1);

            case '\n':
                printf("[MYSHELL] $ ");
                break;

            default:
                // parse input into cmd_argv - store # commands in cmd_argc
                parse_input();

                //check for zombie processes
                check_zombies();

                if(handle_commands() == 0)
                    create_process();
                    printf("\n[MYSHELL] $ ");

        }
    }
    printf("\n[MYSHELL] $ ");
    return 0;
}

解析輸入...我知道,我無法在此框上使用readline :(如果提供了運算符,請在后台創建作業...(請參閱下文)

void parse_input()
{
    // clears command line
    while (cmd_argc != 0) {
        cmd_argv[cmd_argc] = NULL;
        cmd_argc--; 
    }

    buffer_characters = 0;

    // get command line input
    while ((user_input != '\n') && (buffer_characters < 50)) {
        buffer[buffer_characters++] = user_input;
        user_input = getchar();
    }

    // clear buffer
    buffer[buffer_characters] = 0x00;

    // populate cmd_argv - array of commands
    char *buffer_pointer;
    buffer_pointer = strtok(buffer, " ");

    while (buffer_pointer != NULL) { 
        cmd_argv[cmd_argc] = buffer_pointer;
        buffer_pointer = strtok(NULL, " ");

        //check for background process execution
        if(strcmp(cmd_argv[cmd_argc], "&")==0){
            printf("Started job %d\n", getpid());    
            make_background_job();
        }

        cmd_argc++;
    }
}

進行后台工作。 關閉子進程STDIN,打開新的STDIN,然后執行。

void make_background_job()
{
    int pid;
    pid = fork();
    fclose(stdin); // close child's stdin
    fopen("/dev/null", "r"); // open a new stdin that is always empty

    fprintf(stderr, "Child pid = %d\n", getpid());

    //add pid to jobs list
    jobs_list[jobs_list_size] = getpid();
/*     printf("jobs list %d", *jobs_list[jobs_list_size]);         */
    jobs_list_size++;

    execvp(*cmd_argv,cmd_argv);

    // this should never be reached, unless there is an error
    fprintf (stderr, "unknown command: %s\n", cmd_argv[0]);     
}

我的工作控制的肉。 Fork產生子代,子代返回0,父代返回PID。

void create_process()
{   
    pid_t pid;

    pid = fork();
    status = 0;

    switch(pid){
        case -1:
            perror("[MYSHELL ] $ (fork)");
            exit(EXIT_FAILURE);
        case 0:            
            make_background_job();
            printf("\n\n----Just made background job in case 0 of create_process----\n\n");        
            break;

        default:
            printf("\n\n----Default case of create_process----\n\n");
            // parent process, waiting on child...
            waitpid(pid, &status, 0);

            if (status != 0) 
                fprintf  (stderr, "error: %s exited with status code %d\n", cmd_argv[0], status);
            else
                break;
    }
}

我的問題是,當我在后台執行作業時,它執行兩次命令,然后退出外殼。 (否則,如果未啟用任何后台進程,它將正常運行)。 我在哪里感到困惑? 我認為這可能與我的PID有關,因為我沒有在'make_background_job'中正確填充列表

這是我的輸出,example.sh只是拋出helloWorld:

[MYSHELL] $ ./example.sh &
Started job 15479
Child pid = 15479
Child pid = 15481
Hello World
Hello World

似乎發生的是

  • main()中顯示提示,要求輸入命令
  • 輸入命令時,將調用parse_input()
  • 它會構建命令數組,直到找到&並調用make_background_jobs()
  • 該函數快速分叉,並在兩個進程execvp()中並行執行
  • execvp()替換兩個進程中的每個進程以執行命令
  • 因此出現了兩個“ Hello world”。

問題出在make_background_jobs()中,我認為預期的行為是兩個進程中只有一個應該執行該命令,而另一個(父親)返回,以保持程序處於活動狀態。

這可以通過修改該函數來解決,使父進程返回:

    void make_background_job()
    {
      int pid;
      pid = fork();

      if (pid) return; // The father process returns to keep program active
      ...

編輯

我嘗試了一下,刪除了不必要的


void make_background_job()
{
    int pid;
    pid = fork();

    if ( ! pid)
    {
      fclose(stdin); // close child's stdin
      fopen("/dev/null", "r"); // open a new stdin that is always empty

      fprintf(stderr, "Child Job pid = %d\n", getpid());

      //add pid to jobs list
      jobs_list[jobs_list_size] = getpid();
  /*     printf("jobs list %d", *jobs_list[jobs_list_size]);         */
      jobs_list_size++;

      execvp(*cmd_argv,cmd_argv);

    // this should never be reached, unless there is an error
      fprintf (stderr, "unknown command: %s\n", cmd_argv[0]);     
      exit(1);
    }

    waitpid(pid, &status, 0);
}

后台作業是在另一個過程中創建的。 父親等待工作完成。


void parse_input()
{
    // clears command line
    while (cmd_argc != 0) {
        cmd_argv[cmd_argc] = NULL;
        cmd_argc--; 
    }

    buffer_characters = 0;

    // get command line input
    while ((user_input != '\n') && (buffer_characters < 50)) {
        buffer[buffer_characters++] = user_input;
        user_input = getchar();
    }

    // clear buffer
    buffer[buffer_characters] = 0x00;

    // populate cmd_argv - array of commands
    char *buffer_pointer;
    buffer_pointer = strtok(buffer, " ");

    int ok = 0;

    while (buffer_pointer != NULL) { 
        cmd_argv[cmd_argc] = buffer_pointer;
        buffer_pointer = strtok(NULL, " ");

        //check for background process execution
        if(strcmp(cmd_argv[cmd_argc], "&")==0){
          ok = 1;
          break;
        }

        cmd_argc++;
    }

    if (!ok) cmd_argv[cmd_argc = 0] = NULL; // If no & found, reset commands
}

僅解析輸入。

在新的handle_commands()下方,如果有要播放的命令,則返回0 ,隨后是main


int handle_commands() { return cmd_argc > 0 ? 0:1; }

int main(int argc, char **argv)
{           
    printf("[MYSHELL] $ ");

    while (TRUE) {
        user_input = getchar();
        switch (user_input) {

            case EOF:
                exit(-1);

            case '\n':
                printf("[MYSHELL] $ ");
                break;

            default:
                // parse input into cmd_argv - store # commands in cmd_argc
                parse_input();

                //check for zombie processes
                check_zombies();

                if(handle_commands() == 0)
                    make_background_job();  // Call directly the bg job
                    printf("\n[MYSHELL] $ ");

        }
    }
    printf("\n[MYSHELL] $ ");
    return 0;
}

main()直接調用make_background_job()

make_background_job中只有一個fork() create_process()已被刪除。

暫無
暫無

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

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