在基本shell中实现自定义命令(在C中)

时间:2017-09-29 16:48:04

标签: linux bash shell operating-system system-calls

我需要在shell中实现自定义命令。目标是支持创建子进程以执行program_name m的命令program_name,但如果它没有完成其操作则中止该进程以秒为单位。

实际上我每次都在检查waitpid(child_pid,& exit_status,WUNTRACED)的状态,但是for循环中的代码段不起作用,并没有中止进程!! 任何人都可以建议我从库中提供适当的例程,在m秒后发送SIGALRM信号,并使用信号处理程序执行适当的操作吗? 在此先感谢!!

int child_pid = fork();
    if (child_pid < 0) {
        perror("ERROR: could not fork process.\n");
    }
    if (child_pid == 0) {
        char *args[4];
        args[0] = path;
        args[1] = "-c";
        args[2] = command_line;
        args[3] = (char *) 0;

        //executing the command
        int exec_return = execvp(path, args);

        if (exec_return == -1) {
            perror("error: command execution failed!\n");
        } else {
            exit(exec_return);
        }
    } else {
        //assigning cur_fg_pid to the child
        cur_fg_pid = child_pid + 1;
        if (cur_fg_cmd == NULL) { cur_fg_cmd = (char *) malloc(sizeof(char)); }
        strcpy(cur_fg_cmd, command_line);
        int exit_status;
        while (can_wait == 1 && waitpid(child_pid, &exit_status, 0) > 0) {}            
        cur_fg_pid = -1;
        cur_fg_cmd = NULL;
        if (can_wait == 1) latest_jobid = -1;

        if(global_time_flag)
    {
    for (i = 0; i < stip_time; i++) {
         if (waitpid(child_pid,&exit_status,WUNTRACED) > 0)
                if (WIFSTOPPED(exit_status)) {
                        break;
             } else {sleep(1);}

        }
            if(!WIFSTOPPED(exit_status ))
             kill (child_pid, SIGUSR1);
    }
        }

0 个答案:

没有答案