English 中文(简体)
Unix C外壳-作业控制问题!
原标题:Unix C Shell - Job Control Issue!

我一直在用C语言创建自己的Unix Shell,以练习它的交互工作。。。让我的进程在后台运行,同时允许我的shell继续接受用户输入时,我遇到了一些问题。如果你能抽出时间剖析一下我下面的内容,我将不胜感激!

我的变量如下,只是以防万一,这有助于更好地理解事情

#define TRUE 1

static char user_input =   ; 

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  
 :
                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("
[MYSHELL] $ ");

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

Parse Input...I know, I can t get readline to work on this box :( If provided the & operator, create the job in the background... (see below)

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 !=  
 ) && (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
", 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
", 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
", 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("

----Just made background job in case 0 of create_process----

");        
            break;

        default:
            printf("

----Default case of create_process----

");
            // parent process, waiting on child...
            waitpid(pid, &status, 0);

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

我的问题是,当我在后台执行一个作业时,它会执行两次命令,然后退出shell。(如果未启用后台进程,则正常工作)。我哪里糊涂了?我认为这可能与我的PID有关,因为我在make_background_job中也没有正确填充列表

这是我的输出,example.sh只是抛出helloWorld:

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

似乎发生了什么

  • in main() the prompt is displayed, expecting a command
  • when a command is input, parse_input() is called
  • it builds the commands array until it finds & where it calls make_background_jobs()
  • that function forks quickly, and executes in parallel, in two processes, execvp()
  • execvp() replaces each of the two processes to execute the command
  • thus two "Hello world" appear.

问题出现在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
", 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
", 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 !=  
 ) && (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  
 :
                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("
[MYSHELL] $ ");

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

main()直接调用make_background_job()

make_background_job中只有一个fork()create_process()已被删除。

问题回答

暂无回答




相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...

热门标签