更新:当我设置act.sa_flags = SA_RESTART时,程序会停止分段错误,但它会导致程序被卡住"在该函数中,因为它没有继续我的程序中的逻辑。冒号表示新命令行输入的开始。理想的输出如下:
: ls
smallsh.c small
: sleep 5 & //background process
: ls > junk
background pid # is complete terminated by signal $ //when background sleep finishes
:
但是我现在得到以下内容:
: ls
smallsh.c small
: sleep 5 & //background process
: ls > junk
background pid # is complete terminated by signal $
//cursor is pointing here but no colon appears, i can still write commands
//and they will work but function believers they are all background processes
上一篇:我尝试使用C语言中的背景和前台进程编写一个简单的shell。为了创建后台进程,用户必须输入一个"&"在他们的命令结束时,例如"睡眠3&"将是一个后台进程。在我进入"睡眠3&"该过程成功运行,但在完成调用sig处理函数时,将打印一个语句(表明后台进程已结束),然后程序seg出错。以下是输出结果的示例:
:睡3& 背景pid是22688 :后台pid 0完成:由信号0终止 分段错误:11
当我尝试运行后台进程并且我不确定原因时,会调用我的信号处理程序。当我设置sigaction以使用SIGINT时,程序不会出错。有什么想法吗?我在这里看到了类似的帖子(SIGCHLD causing segmentation fault, not going into handler)但它并没有帮助我。
pid_t spawnPID = -5
int exitMethod;
int exitStatus = 0;
char bgPID[10];
//Set up signal handler
struct sigaction act;
act.sa_handler = sig_handler;
act.sa_flags = 0;
sigfillset(&(act.sa_mask));
fflush(stdout);
if (bg == 1)
{
sigaction(SIGCHLD, &act, NULL);
}
switch(spawnPID)
{
case -1:
{
//There was an error forking
printf("Error forking\n");
fflush(stdout);
exitStatus = 1;
}
case 0: //Child process
{
//Check for input/output redirection
if (numArgs > 1)
{
if (!(strncmp(arguments[1], ">", 1)))
{
exitStatus = outputRedirect(arguments,numArgs);
}
else if (!(strncmp(arguments[1], "<", 1)) || (!
(strncmp(arguments[0], "cat", 1))))
{
exitStatus = inputRedirect(arguments,numArgs);
}
else
{
arguments[numArgs] = NULL; //set last value in the array to NULL
if (execvp(arguments[0],arguments) == -1)
{
printf("Command or file not recognized\n"); //won't run unless there is an error
fflush(stdout);
exitStatus = 1;
}
}
}
else //run other command
{
if (execvp(arguments[0],arguments) == -1)
{
printf("%s: No such command, file or directory\n", arguments[0]); //won't run unless there is an error
fflush(stdout);
exitStatus = 1;
}
}
break;
}
//Following code is in the parent case of the switch statement
default:
if (bg == 0) //waitpid is only called in a parent in a foreground process
{
pid_t exitpid = waitpid(spawnPID,&exitMethod,0); //Wait for one of the
//children to be completed
{
if (WIFEXITED(exitMethod))
{
int exitStatus = WEXITSTATUS(exitMethod);
}
//Sig Handler function
void sig_handler (int signo)
{
int status;
pid_t childPid;
char bgMessage[50];
char bgPID[10];
char exitStatus[10];
childPid = waitpid(-1, &status, 0);
sprintf(bgPID,"%d",childPid);
sprintf(exitStatus,"%d",WEXITSTATUS(status));
strcat(bgMessage,"background pid ");
strcat(bgMessage,bgPID);
strcat(bgMessage," is done: terminated by signal " );
strcat(bgMessage,exitStatus);
strcat(bgMessage,"\n");
// Write out the message
write(1, bgMessage, sizeof(bgMessage));
}