【发布时间】:2015-09-29 17:13:22
【问题描述】:
我正在用 C 语言创建一个程序,例如终端 shell,这是我在课堂上的练习。如果您在句末添加“&”,该程序允许同时运行多个进程。 (例如:$ gedit &);但是,我的代码只是在子进程退出时运行父进程。
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
void parse(char *line, char **argv)
{
while (*line != '\0') { /* if not the end of line ....... */
while (*line == ' ' || *line == '\t' || *line == '\n')
*line++ = '\0'; /* replace white spaces with 0 */
*argv++ = line; /* save the argument position */
while (*line != '\0' && *line != ' ' &&
*line != '\t' && *line != '\n')
line++; /* skip the argument until ... */
}
*argv = '\0'; /* mark the end of argument list */
}
void execute(char **argv)
{
pid_t pid;
int status;
if ((pid = fork()) < 0) { /* fork a child process */
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) { /* for the child process: */
if (execvp(*argv, argv) < 0) { /* execute the command */
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else { /* for the parent: */
wait(NULL); /* wait for completion */
}
}
void main(void)
{
char line[1024]; /* the input line */
char *argv[64]; /* the command line argument */
while (1) { /* repeat until done .... */
printf("COMMAND -> "); /* display a prompt */
gets(line); /* read in the command line */
printf("\n");
parse(line, argv); /* parse the line */
if (strcmp(argv[0], "exit") == 0) /* is it an "exit"? */
exit(0); /* exit if it is */
execute(argv); /* otherwise, execute the command */
}
}
我想要这样的结果:
例如:$ gedit & // 程序 gedit 以 pid = 4789 运行
$ emacs // 程序 emacs 以 pid = 5123 ppid = 4789 运行
【问题讨论】:
-
想必父进程正在等待,因为它调用了
wait函数。 -
@Adrian:我知道;但我不知道如何执行多个进程。
-
我不明白你在问什么。您是在问如何运行多个 child 进程吗?然后您需要多次致电
fork。当然,你不能在父进程等待的时候调用fork,所以你需要想办法解决这个问题。