2

我正在尝试构建一个作业控制外壳,目前正在处理后台进程。在这个程序中,我 fork 一个子进程来处理每个后台进程,并且在 fork 之后立即得到提示。但问题是,当后台进程返回时,又会打印出提示信息。有人可以帮我解决这个问题吗?谢谢 ##

char prompt[] = "myShell";
set_sighandler_SIGCHLD();  //wait for background process return
while(1){
       char cmd[BUFFERSIZE] = "";
       write(1, prompt, sizeof(prompt));
       if(read(0, cmd, 1024) <= 1)){
              //parse command
              //and execute
       }
}
//Here is the background process.
int put_to_background(int (*func)(char** arg), char ** cmd){
     pid_t pid;
     if((pid = fork()) < 0){
         perror("fork");
         return -1;
     }
     else if(pid == 0){
         func(cmd);     //call the function the execute the command
         _exit(0);
     }
     else{
         if(setpgid(pid, 0)){
             perror("setpgid");
             return -1;
         }
         printf("running: %d\n", pid);

     }

在我调用函数后,它立即打印出提示“myShell”(这是我所期望的),但在后台进程返回后又打印了一次。

我仍在研究信号处理...

 JobList list;
 void sighandler(int signum, siginfo_t *sip, void *ucp){
     if(signum == SIGCHLD){
        pid_t pid;
        while((pid = waitpid(-1, NULL, WNOHANG)) > 0){
           Job * job = (Job*)malloc(sizeof(Job));
           job->pid = pid;
           insert(&list, job);  
       }
     }
     else if(signum == SIGTTOU){
       printf("SIGTTOU: pid = %d\n", (int) sip->si_pid);
     }
     else if(signum == SIGTTIN){
      printf("SIGTTIN: pid = %d\n", (int) sip->si_pid);
     }
 }  

int set_sighandler_SIGCHLD(){

struct sigaction sa;
sigemptyset(&sa.sa_mask);

sigaddset(&sa.sa_mask, SIGCHLD); 
sigaddset(&sa.sa_mask, SIGTTIN);
sigaddset(&sa.sa_mask, SIGTTOU);
sa.sa_sigaction = sighandler;
sa.sa_flags = SA_SIGINFO;
//sigprocmask(SIG_BLOCK, &sa.sa_mask, NULL);

if(sigaction(SIGCHLD, &sa, NULL)){
    perror("sigaction");
    return -1;
}
if(sigaction(SIGTTOU, &sa, NULL)){
    perror("sigaction");
    return -1;
}
if(sigaction(SIGTTIN, &sa, NULL)){
    perror("sigaction");
    return -1;
}
return 0;

}

4

1 回答 1

0

The read loop is being interrupted by the signal, so you print the prompt. (That is, when the signal arrives, read immediately returns.) You can either check if read returns -1 and has returned due to EINTR, or try setting SA_RESTART to the signal handler. Note that SA_RESTART does not always work (implementation dependent, many bugs in various implementations) and is, IMO, best avoided.

于 2012-05-28T13:00:18.653 回答