In: Computer Science
UNIX
1. Compile and run shell0.c file
2. Design and implement shell1.c program to handle "exit"
command to terminate the program.
That is, if the user input-string is "exit", then the program
terminates.
3.Design and Implement shell2.c to implement a signal handler to handle ctrl+C (SIGINT) as listed below
void sig_int(int signo) { printf("\nCaught SIGINT!\n"); }
Here is shell0.c file
shell0.c
/*
* shell0.c
* running in loop to read input string (command) to be processed
* To exit, type EOF (ctlr+D) or ctlr+C
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
char *getinput(char *buffer, size_t buflen)
{
printf("$$ ");
return fgets(buffer, buflen, stdin);
}
int main(int argc, char **argv)
{
char buf[1024];
pid_t pid;
int status;
while (getinput(buf, sizeof(buf))) {
buf[strlen(buf) - 1] = '\0';
if((pid=fork()) == -1) {
fprintf(stderr, "shell: can't fork: %s\n",
strerror(errno));
continue;
} else if (pid == 0) {
/* child */
execlp(buf, buf, (char *)0);
fprintf(stderr, "shell: couldn't exec %s: %s\n", buf,
strerror(errno));
exit(EX_DATAERR);
}
if ((pid=waitpid(pid, &status, 0)) < 0)
fprintf(stderr, "shell: waitpid error: %s\n",
strerror(errno));
}
exit(EX_OK);
}
Here is shell1.c
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
int main(int argc, char **argv)
{
char buf[1024];
do {
//write your code here
}
while (strcasecmp(getinput(buf, sizeof(buf)),"exit"));
return 0;
}
This will exit the program in unix if user type string exit.
shell2.c
#include<stdio.h>
#include<signal.h>
#include<unistd.h>
void sig_int(int signo) {
if (signo == SIGINT){
printf("\nCaught SIGINT!\n");
}
}
int main(void)
{
if (signal(SIGINT, sig_int) == SIG_ERR)
while(1)
sleep(1);
return 0;
}
Here it will stop ctrl+C (SIGINT) from exit and would indiake print Caught SIGINT each time when user presses ctrl+C. We have also used a long wait to issue signal to process.