首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

又开子进程,freopen就不顶用了。

2013-07-01 
再开子进程,freopen就不顶用了。。。int SimShell::shell_main(char *args)//传个命令参数,模拟shell的功能主

再开子进程,freopen就不顶用了。。。



int SimShell::shell_main(char *args)//传个命令参数,模拟shell的功能主要用fork和execvp
{
//char arg[BUFSIZE];
ssize_t readbytes;  //long型
char str_prompt[BUFSIZE + 1];

//while(1)
    //{
  
    freopen("/season/output.txt", "w", stdout);
    

    //if(arg[readbytes - 1] == '\n')
    //{ /* clear '\n' at end of arg */
      //  arg[readbytes - 1] = '\0';
    //} 
    
    if(isquit(args) == 1)
    { /* check quit or not */
        //break;
        return 0;
    }
    
    //int dealarg(char *arg);
    dealarg(args);
    fprintf(stdout, "%s", shell_prompt(str_prompt));
    fflush(stdout);
    fclose(stdout);
    
//}
    
return 0;
}
int SimShell::dealarg(char *arg)
{
int cmdnum;
char *args[CMDNUMBER];
int argnum;

//int parse_args(char *args[], char *arg); 
argnum = parse_args(args, arg);
args[argnum] = NULL;
    
#if DEBUG
int i;
 
#endif
//int get_cmdnum(char *cmd)
cmdnum = get_cmdnum(args[0]);

switch(cmdnum){
        case SHELL_EMPTY:
            break;
        case SHELL_CD:
            //int shell_cd(char *args[])
            shell_cd(args);
            break;
        case SHELL_FORK:
            //int shell_fork(char *args[])
            shell_fork(args);
            break;
        default:
            fprintf(stdout, "%s:%d: getcmd failed\n", __FILE__, __LINE__);//
            break;
}
    //fclose(shell_fp);
return 0;
}

/*
 * fork and called exec
 */
int SimShell::shell_fork(char *args[])
{
pid_t pid[CMDNUMBER];
int status;
int fork_num;
char **p;/* point args */
char *q;/* point *args */
    
/* get numbers of child process*/
fork_num = 1;
p = args;
while(*p != NULL)
    {
q = *p;
while(*q != '\0')
        {


if(*q == '|')
            {
fork_num++;
}
q++;
}
p++;
}
    
#if DEBUG
    
//fprintf(stdout, "fork_num = %d\n", fork_num);
    
#endif
    
/* case: child process number is one */
if(fork_num < 2){
//pid_t fork(void);
if((pid[0] = fork()) < 0)
        {
/* error */
perror("fork");
exit(1);
}
        else if(pid[0] == 0)
        {
/* child process */
//int execvp(const char *file, char *const argv[]);
if(execvp(args[0], args) < 0)
            {
perror("");
exit(1);
}
            
exit(0);
}
}
    //freopen("/season/out.txt", "a+", stdout);
/* parent process */
//pid_t waitpid(pid_t pid, int *status, int options);
if(fork_num < 2)
    {
waitpid(pid[0], &status, 0);
}
    else
    {
//int mutifork(char *args[])
status = mutifork(args);
        
}
return status;
}



[解决办法]
o  y~~~~~

热点排行