如何在C中创建可以在后台运行程序的shell?

时间:2013-11-20 20:33:33

标签: c shell unix command-line

我知道在子进程中我必须调用setpgrp(),但我不确定如何处理父进程。我知道父母不应该打电话给wait(),但我该如何做呢?如果用户在他/她的命令之后键入&,我希望有一个在后台运行程序的shell。

我的代码如下:

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#define BUFFER_SIZE 1<<16
#define ARRAY_SIZE 1<<16

static void parseCmdArgs(char *buffer, char** cmdArgs, 
                size_t cmdArgsSize, size_t *nargs)
{
    char *bufCmdArgs[cmdArgsSize]; 
    char **temp;
    char *buf;
    size_t n, p;

    cmdArgs[0] = buf = bufCmdArgs[0] = buffer;  

    for(temp=bufCmdArgs; (*temp=strsep(&buf, " \n\t")) != NULL ;){
        if ((*temp != '\0') && (++temp >= &bufCmdArgs[cmdArgsSize]))
            break;
    }

    for (p=n=0; bufCmdArgs[n]!=NULL; n++){
        if(strlen(bufCmdArgs[n])>0)
            cmdArgs[p++]=bufCmdArgs[n];
    }

    *nargs=p;
    cmdArgs[p]=NULL;
}
  //int main(int argc, char *argv[], char *envp[]){
int main(void)
{
    char buffer[BUFFER_SIZE];
    char *args[ARRAY_SIZE];
    int retStatus;
    size_t nargs;
    pid_t pid;

    printf("$dummyshell\n");
    while(1){

        printf("> ");
        fgets(buffer, BUFFER_SIZE, stdin);
        parseCmdArgs(buffer, args, ARRAY_SIZE, &nargs); 


        if (nargs==0)
            continue;

        if (!strcmp(args[0], "help"))
        {
            printf("cat                    cd (absolute path references only\n");
            printf("exit\n");
            printf("help                   history\n");
            printf("jobs                   kill\n");
            printf("ls                     more\n");
            printf("ps                     pwd\n");
            continue;
        }

        if (!strcmp(args[0], "exit" ))
            exit(0);


    pid = fork();
    if (pid == 0)
      setpgrp();//Is this right?
    else if (pid > 0)
      pid = wait(&retStatus);//What do I do here?
    else {
      if (execvp(args[0], args)){
        fprintf(stderr, "%s\n", strerror(errno));
        exit(127);
      }
    }

    }    
    return 0;
}

0 个答案:

没有答案