I am trying to write subshell in linux with c
. I am compiling it in normal linux terminal and run it like ./shell
. However, I have trouble about Ctrl-Z
and Ctrl-C
. When I press the Ctrl-Z
for example, it stops ./myshell
, but I want to stop process which is in the myshell
.
I am setting new process group after the for like:
int pid = fork();
if (!setpgid(pid, 0)) {
} else {
perror("PGID Error: ");
return(-1);
}
After I check is there any &
sign for background process I understand it is foreground process then I put new process into foreground then I am waiting the finish or stop of process with waitpid
. Then I put terminal into foreground. In there I am using sigprocmask
for SIGTTOU
, otherwise when I try to put my shell again into foreground it stops backs to linux shell.
tcsetpgrp(1,getpgid(pid));
waitpid(pid, NULL, 0);
if (sigprocmask(SIG_BLOCK, &intmask, NULL) == -1)
perror("sigprocmask error: ");
tcsetpgrp(1, shellpid);
kill(shellpid, SIGCONT);
if (sigprocmask(SIG_UNBLOCK, &intmask, NULL) == -1)
perror("sigprocmask error: ");
I have also signal handlers to avoid my_shell
to terminate or stop. I am planning the stop or terminate just foreground processes with Control-Z
and Control-C
.
void handler_sigint(int signum)
{
pid_t foregroundpgid=tcgetpgrp(0);
if(foregroundpgid!=shellpid) {
kill(foregroundpgid, SIGINT);
}
}
void handler_sigtstp(int sig)
{
pid_t foregroundpgid=tcgetpgrp(0);
if(foregroundpgid!=shellpid) {
kill(foregroundpgid, SIGSTOP);
}
}
Control-C
works very well but I have trouble with Control-Z
. For example I start cat
in my shell when I press Control-Z
it just writes ^Z
in the terminal does not stop foreground process. Please look at the picture