我在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 */
}
}
我想结果如下:
Ex:$ gedit&amp; //使用pid = 4789运行程序gedit
$ emacs //程序emacs使用pid = 5123 ppid = 4789
运行答案 0 :(得分:0)
如果您看到&符号,请忽略wait()
:
void execute(char **argv, int block)
{
pid_t pid;
int status;
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) {
if (execvp(*argv, argv) < 0) {
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else if (block) {
wait(NULL);
}
}