与其他许多实例一样,我正在尝试模拟外壳。我已经在来自用户的字符串上正确使用execvp
。解析该字符串并生成一个字符串数组(每个单词都有其数组,在space
字符上拆分),最后包括一个NULL
。
当我发现用户输入的最后一个单词是&
时,我设置了一个标志来通知我的shell该命令将在后台执行,同时让用户立即输入另一个命令。 “背景执行”命令在传递给&
的字符串数组中看到其NULL
被execvp
字符替换。
实际上,我一直在尝试使用pthread
在后台运行该进程,但是这样做有些奇怪:通过线程功能传递给execvp
的命令要求我发送命令后,按两次ENTER
。
这是我简化的main
函数,用于模拟shell:
int main (void) {
fprintf (stdout, "%% ");
bool running = true;
while(running) {
/* Ask for an instruction and parses it. */
char** args = query_and_split_input();
/* Executing the commands. */
if (args == NULL) { // error while reading input
running = false;
} else {
printf("shell processing new command\n");
int count = count_words(args);
split_line* line = form_split_line(args, count);
Expression* ast = parse_line(line, 0, line->size - 1);
if(line->thread_flag) {
pthread_t cmd_thr;
/* Setting up the content of the thread. */
thread_data_t thr_data;
thr_data.ast = *ast;
thr_data.line = *line;
/* Executing the thread. */
int thr_err;
if ((thr_err = pthread_create(&cmd_thr, NULL, thr_func, &thr_data))) {
fprintf(stderr, "error: pthread_create, rc: %d\n", thr_err);
return EXIT_FAILURE;
}
printf("thread has been created.\n");
} else {
run_shell(args);
}
free(line);
printf("done running shell on one command\n");
}
}
/* We're all done here. See you! */
printf("Bye!\n");
exit (0);
}
这是我线程的功能:
void *thr_func(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
data->line.content[data->line.size-1] = NULL; // to replace the trailing '&' from the command
run_shell(data->line.content);
printf("thread should have ran the command\n");
pthread_exit(NULL);
}
运行命令的实际行:
void run_shell(char** args) {
/* Forking. */
int status;
pid_t pid; /* Right here, the created THREAD somehow awaits a second 'ENTER' before going on and executing the next instruction that forks the process. This is the subject of my first question. */
pid = fork();
if (pid < 0) {
fprintf(stderr, "fork failed");
} else if (pid == 0) { // child
printf("Child executing the command.\n");
/* Executing the commands. */
execvp(args[0], args);
/* Child process failed. */
printf("execvp didn't finish properly: running exit on child process\n");
exit(-1);
} else { // back in parent
waitpid(-1, &status, 0); // wait for child to finish
if (WIFEXITED(status)) { printf("OK: Child exited with exit status %d.\n", WEXITSTATUS(status)); }
else { printf("ERROR: Child has not terminated correctly. Status is: %d\n", status); }
free(args);
printf("Terminating parent of the child.\n");
}
}
因此,基本上,例如,run_shell(args)
接收的是["echo","bob","is","great",NULL]
(在顺序执行的情况下)或["echo","bob","is","great",NULL,NULL]
(在要执行的命令中背景)。
我已经离开了printf
跟踪,因为它可以帮助您了解执行流程。
如果我输入echo bob is great
,则输出(打印轨迹)为:
shell processing new command
Child executing the command.
bob is great
OK: Child exited with exit status 0.
Terminating parent of the child.
done running shell on one command
但是,如果我输入echo bob is great &
,则输出为:
shell processing new command
thread has been created.
done running shell on one command
然后我实际上需要再次按ENTER
来获得以下输出:
Child executing the command.
bob is great
OK: Child exited with exit status 0.
Terminating parent of the child.
thread should have ran the command
(在最后一次执行时,我还获得了查询和解析用户输入的函数的痕迹,但这似乎无关紧要,因此我将整个部分进行了抽象。)
所以我的问题是:
ENTER
之前等待第二个execvp
? (thr_func
停止执行run_shell
,并等待ENTER
指令之前的第二个pid = fork();
)答案 0 :(得分:2)
您不能使用线程来模拟进程。好吧,严格来说可以,但是这样做是没有用的。问题是属于一个进程的所有线程共享相同的虚拟地址空间。没有理由创建线程,因为您最终需要fork()
来创建一个新进程(出于下面说明的原因,您将需要此线程),因此,如果其中一个线程将被停止,为什么还要创建两个执行线程一直在等待子进程完成。在该架构上没有用。
从历史上来看,需要fork()
系统调用是为了创建一个新进程(具有不同的虚拟内存映射)以进行简单的调用,以允许执行新程序。您需要先创建一个完整的新进程,然后再调用exec(2)
系统调用,因为进程地址空间将被新程序的text和data段覆盖。如果在线程中执行此操作,则将覆盖整个进程地址空间(这是外壳),并杀死所有可以代表该进程运行的线程。遵循的架构是(伪代码):
/* create pipes for redirection here, before fork()ing, so they are available
* in the parent process and the child process */
int fds[2];
if (pipe(fds) < 0) { /* error */
... /* do error treatment */
}
pid_t child_pid = fork();
switch(child_pid) {
case -1: /* fork failed for some reason, no subprocess created */
...
break;
case 0: /* this code is executed in the childd process, do redirections
* here on pipes acquired ***before*** the fork() call */
if (dup2(0 /* or 1, or 2... */, fds[0 /* or 1, or 2... */]) < 0) { /* error */
... /* do error management, considering you are in a different process now */
}
execvpe(argc, argv, envp);
... /* do error management, as execvpe failed (exec* is non-returning if ok) */
break; /* or exit(2) or whatever */
default: /* we are the parent, use the return value to track the child */
save_child_pid(child_pid);
... /* close the unused file descriptors */
close(fds[1 /* or 0, or 2, ... */]);
... /* more bookkeeping */
/* next depends on if you have to wait for the child or not */
wait*(...); /* wait has several flavours */
} /* switch */
Exec和fork系统调用有两个原因:
exec()
之前在子级中执行实际的重定向。仅当您可能需要使用不同的线程来执行任务时,才需要与每个孩子进行通信的线程。但是,请考虑一个线程与父对象共享所有虚拟空间(我们可以讨论线程之间的父/子关系),如果执行exec调用,整个过程将覆盖该虚拟空间(所有线程在那里)