C 如何将信号传递给子进程
标题可能有点混乱,所以让我解释一下。我试图写一个简单的shell来练习我的编程。我已经得到了get a命令,fork,exec循环的工作。然而,当我在子进程仍在执行时按CTRL-C时,shell终止,而不是子进程(但子进程将继续运行)。以下是主要功能:C 如何将信号传递给子进程,c,shell,io,C,Shell,Io,标题可能有点混乱,所以让我解释一下。我试图写一个简单的shell来练习我的编程。我已经得到了get a命令,fork,exec循环的工作。然而,当我在子进程仍在执行时按CTRL-C时,shell终止,而不是子进程(但子进程将继续运行)。以下是主要功能: int main() { dynarray *args; /* pointer to a dynamic array */ int bytes_read; size_t nbytes = 0; char *comm
int main()
{
dynarray *args; /* pointer to a dynamic array */
int bytes_read;
size_t nbytes = 0;
char *command;
pid_t pid;
printf("Enter command: ");
while ((bytes_read = getline(&command, &nbytes, stdin)) != -1) {
if (bytes_read == -1) {
perror("getline");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (pid == 0) { /* child process */
args = newdynarray();
char *arg = strtok(command, " \n");
while (arg != NULL) {
addstring(args, arg);
arg = strtok(NULL, " \n");
}
if (args->nval == 0) {
freedynarray(args);
continue;
}
addstring(args, NULL);
char *fullpath = find_executable(args->strings[0]);
if (fullpath == NULL) {
fprintf(stderr, "Couldn't find executable: %s\n", command);
exit(EXIT_FAILURE);
}
if (execv(fullpath, args->strings) == -1) {
perror("execv");
exit(EXIT_FAILURE);
}
} else {
int status;
waitpid(pid, &status, 0);
}
printf("Enter command: ");
}
return 0;
}
我没有包括其他部分,因为我认为它们不相关。如何使我的子进程捕获来自stdin的所有输入,直到它终止?您可以在父进程中为
SIGINT
注册一个信号处理程序,并在其中使用kill(2)
向子进程发送信号,您应该将其PID存储在某个位置。如何使我的子进程捕获来自stdin的所有输入,直到它终止?
从stdin键(如控件C)生成的信号将发送到最后一个进程以使用stdin,因此除非您可以强制您的子进程使用该路径,否则您将无能为力
相反,您需要在shell进程中创建一个信号处理程序来捕获SIGINT(和其他信号),并将信号(使用kill()
函数)重新发送到您想要接收它的进程