我一直在用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