C语言 通过子进程终止父进程



我的任务是实现这个镜像Linux shell的myshell程序。这是我大学的操作系统入门课程的范围。他们向我们提供了基本的shell代码,并要求我们对其进行修改。

其中一个练习是实现一个exit命令来终止自定义shell。我使用strcmp来做这个。然而,我觉得这是一个非常黑客的解决方案-感觉像作弊。

源代码:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char* argv[]){
char buf[1024];
char* args[256];
pid_t pid;
for( ; ; ){
char* command;
fprintf(stdout, "$ ");
if((command = fgets(buf, sizeof(buf), stdin)) == NULL){
break;
}
command[strlen(buf) -1] = '';
//saving commands to a memory file so I can 
//print them out later on with tail (through 
//myhistory)
FILE* f = fopen("mem.txt", "a");
fwrite(command, sizeof(char), strlen(command), f);
fputc('n', f);
fclose(f);
int i = 0;
do{
if(i == 0) args[i] = strtok(command, " ");
else args[i] = strtok(NULL, " ");
i++;
}while(args[i-1] != NULL);
//hacky exit command I'm trying to improve on
if(!strcmp(args[0], "exit")) exit(EXIT_SUCCESS);
if((pid = fork()) == -1){
fprintf(stderr, "%s: cant fork command: %s", 
argv[0], strerror(errno));
continue;
} else if (pid == 0){
execvp(args[0], args);
fprintf(stderr, "%s: couldn't exec %s: %sn", 
argv[0], buf, strerror(errno));
exit(EXIT_FAILURE);
}  
if((pid = waitpid(pid, NULL, 0)) < 0)
fprintf(stderr, "%s: waitpid error: %sn",
argv[0], strerror(errno));
}
exit(EXIT_SUCCESS);
}

我这样写退出命令:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
int main(){
kill(getpid(), 0);
}

然而,这没有用,因为我只是在杀死这个孩子。我怎么能通过孩子杀死父母呢?是的,我知道我可以将父PID传递给退出命令并以这种方式终止它,但有些东西告诉我有一个更干净的解决方案,不需要硬编码控制流逻辑。

In "real"shell,像exit这样的命令是一个"内置"的shell。它们不是启动另一个程序的外部命令,而是由shell内部执行的。

你可以通过各种方式实现它们,strcmp, dictionary等,但它们本质上只是你当前所做的事情的美化版本。所以,是的,继续做你正在做的。

最新更新