ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
i am trying to build a simple shell program that allow me to run commands in foreground and background modes .
in case of foreground i think its work fine but when i run a command i a background mode by adding & at the end of the command the program freezes until i press enter then i get the segmentaion fault error .
kindly take a look at this code an let me know where is the mistake .
thanks
Code:
// simple shell
// executes one command a time without arguments and flags
// not supports pipelines
// not supports input/output redirection
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAXLINE 2048
enum {FOREGROUND,BACKGROUND};
static volatile sig_atomic_t sigflag; /* set nonzero by sig handler */
static sigset_t newmask, oldmask, zeromask;
void executeCommand(char *cmd);
void forkProcess(char **,int cnt);
void wait_child(void);
void collect_child();
void sig_handler();
int main(void)
{
char buf[MAXLINE];
printf("smash:>"); /* print prompt (printf requires %% to print %) */
while (fgets(buf, MAXLINE, stdin)!=NULL)
{
buf[strlen(buf) - 1] = 0; /* replace newline with null */
executeCommand(buf);
printf("smash:>");
}
exit(0);
}
void executeCommand(char *cmd)
{
char **argsList=NULL;
int argsCnt=0;
char *ptr;
char *tmpCmd=strdup(cmd);
ptr=strtok(tmpCmd," ");
while(ptr!=NULL)
{
argsList=(char**)realloc(argsList,sizeof(char**)*(++argsCnt)+1);
argsList[argsCnt-1]=strdup(ptr);
ptr=strtok(NULL," ");
}
argsList[argsCnt]=NULL;
if(strcmp(argsList[0],"exit")==0)
{
if(argsCnt==1)
{
printf("Bye\n");
exit(0);
}
else
printf("error : exit does'nt accept arguments.\n") ;
}
else if(strcmp(argsList[0],"cd")==0)
{
if(argsCnt==2)
chdir(argsList[1]);
else
printf("error : invalid number of arguments for cd.\n");
}
else
forkProcess(argsList,argsCnt);
}
void forkProcess(char **argsList,int cnt)
{
pid_t pid;
int runStyle;
if(strcmp(argsList[cnt-1],"&")==0)
{
runStyle=BACKGROUND ;
argsList[cnt-1]=NULL;
}
else
runStyle=FOREGROUND;
if ( (pid = fork()) < 0)
fprintf(stderr,"fork error");
if (pid == 0)
{
if (execvp(argsList[0], argsList)< 0)
fprintf(stderr,"execl error");
}
else //parent
{
if(runStyle==FOREGROUND)
{
printf("waitttt\n");
wait_child();
}
else
{
if (signal(SIGCHLD, sig_handler) == SIG_ERR)
printf("signal(SIGUSR1) error");
}
}
}
void sig_handler()
{
pid_t pid;
int status;
printf("sig handler\n");
sigflag = 1;
if ((pid=wait(&status)) < 0)
{
perror("Wait failed\n");
exit(3);
}
else
{
if (WIFEXITED(status))
printf ("Pid %d terminated with status %d\n", pid, WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf ("Pid %d terminated by signal %d\n", pid, WTERMSIG(status));
}
}
void wait_child(void){
if (signal(SIGCHLD, sig_handler) == SIG_ERR)
printf("signal(SIGUSR1) error");
sigemptyset(&zeromask);
sigemptyset(&newmask);
sigaddset(&newmask, SIGCHLD);
if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0)
printf("SIG_BLOCK error");
while (sigflag == 0)
sigsuspend(&zeromask); /* and wait for child */
sigflag = 0; /* * Reset signal mask to original value. */
if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
printf("SIG_SETMASK error");
}
Of course the program is supposed to "freeze" until you press <Enter>. Function fgets() gets a whole line (usually) from the keyboard, and doesn't return control to your program until you press the <Enter> key.
As far as the segmentation fault goes, I recommend using gdb.
its freezing after entering a command and hit enter
for example if i enter
smash:>ls & <enter>
the command run and give the output and i get a message that the command exits with status 0
but then it freeze and if i hit a key i get the segmentaion fault.
its freezing after entering a command and hit enter
for example if i enter
smash:>ls & <enter>
the command run and give the output and i get a message that the command exits with status 0
but then it freeze and if i hit a key i get the segmentaion fault.
so its not related to the fgets
Note that you are invoking the fgets function in a loop. If you look at your forkProcess function, it will not return in the child process scenario, however for the parent code it WILL return. Consequently fgets would get invoked again, and the parent program would once again await user input.
I'm confused as to what you experience, and I may also not be clear on what you expect.
It's a good thing that you posted the program itself. That's a start. Now, could you please use the program script to run your program and demonstrate its misbehavior? Then exit out of script and post the content of file typescript to this thread? That way we'll get a clear picture of what's happening when you run the program.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.