我正在写一个C程序。所有代码都在while循环中,但我还没有添加它。它需要来自用户的输入,例如start ls -l
并运行ls -l
。等待新命令。如果用户写“等待”并且有一个未结束的进程,它将等待子进程完成并打印刚刚完成的子进程ID并接受新命令。我的等待命令不起作用,我需要你的帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main (int argc, char **argv)
{
char command[1024];
char *cmd;
char *ptr1;
char *ptr2 = (char*)malloc(10 * sizeof(char));
char *ptr3;
char *pos;
char *args[3];
char tmp[1024];
int count = 0;
int cstatus;
pid_t child;
pid_t c;
printf("newShell> ");
fgets( command, 1024, stdin );
if ((pos=strchr(command, '\n')) != NULL)
*pos = '\0';
if (strlen(command) > 1024)
{
printf("Command is too long\n");
exit(1);
}
strcpy(tmp,command);
ptr1 = strtok(tmp," ");
cmd = ptr1;
while(ptr1 != NULL)
{
ptr1 = strtok(NULL, " ");
if (ptr1 == NULL) break;
if (count == 0)
{
ptr3 = ptr1;
count = 1;
}
else
strcat(strcat(ptr2,ptr1)," ");
}
ptr2[strlen(ptr2) - 1] = '\0';
args[0] = ptr3;
args[1] = ptr2;
args[2] = NULL;
if (strcmp(cmd,"start") == 0)
{
if ((child = fork()) == 0)
{
printf("\nProcess %ld is started\n", (long) getpid());
execvp(args[0], args);
fprintf(stderr, "execvp() couldn't do the process\n");
exit(1);
}
if (child == (pid_t)(-1))
{
fprintf(stderr, "Fork error.\n"); exit(1);
}
}
else if (strcmp(cmd,"wait") == 0)
{
if (child > 0)
{
c = wait(&cstatus);
printf("Process %ld completed with code: %d \n",
(long) c, cstatus);
}
else
printf("There is no process\n");
}
}
编辑:
我应该用以下内容更改该部分:
child = fork();
if (child == (pid_t)(-1))
{
fprintf(stderr, "Fork failed.\n");
exit(1);
}
if (strcmp(cmd,"start") == 0)
{
if (child == 0)
{
printf("\nProcess %ld is started\n", (long) getpid());
execvp(args[0], args);
fprintf(stderr, "execvp() couldn't do the process\n");
exit(1);
continue;
}
else if (strcmp(cmd,"wait") == 0)
c = wait(&cstatus);
printf("Parent: Child %ld exited with status = %d\n",
(long) c, cstatus);
continue;
}
答案 0 :(得分:2)
进程只能等待自己的子进程。您需要将while
循环添加到您的程序中,以便它可以等待它分叉的子节点。您无法重新运行该程序并等待上一次调用启动的进程,因为该进程不是它的子进程。
所以你需要在你的程序中添加while循环。
while (1) {
printf("newShell> ");
fgets( command, 1024, stdin );
... // all the rest of your code
}
请注意,您可能无法找到newShell>
提示。由于您的程序在返回循环开始之前不会等待子进程,因此它通常会在子进程运行之前打印提示并打印其输出。