更新:当我设置 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。为了创建后台进程,用户必须在命令末尾输入一个“&”,例如“sleep 3 &”将是一个后台进程。在我的程序中,当我输入“sleep 3 &”时,进程成功运行,但在调用 sig 处理函数时完成后打印一条语句(表明后台进程已结束),然后程序段出错。这是输出的示例:
:睡眠 3 和后台 pid 为 22688:后台 pid 0 已完成:由信号 0 终止 分段错误:11
当我尝试运行后台进程时会调用我的信号处理程序,但我不确定为什么。当我将 sigaction 设置为使用 SIGINT 时,程序不会出现段错误。有什么想法吗?我在这里看到了一个类似的帖子(SIGCHLD 导致分段错误,而不是进入处理程序),但这对我没有帮助。
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));
}