标题可能有点令人困惑,所以让我解释一下。我正在尝试编写一个简单的 shell 来练习我的编程。我已经得到一个命令,fork,exec 循环工作。但是,当我在子进程仍在执行时按 CTRL-C 时,我的 shell 将终止,而不是子进程(但子进程将继续运行)。主要功能如下:
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存储在某个地方。
关于c - 如何将信号传递给子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10672829/