繁体   English   中英

尝试派生一个进程,第一个命令有效,但第二个始终给出错误

[英]Trying to fork a process, first command works but second always gives an error

因此,当前我正在创建一个接受用户命令的Shell接口,然后在一个单独的进程中执行每个命令。 我花了一些时间才能将输入正确输入到字符数组中。 (必须解析它并划分每个输入,即args [0] = ls,args [1] = -l)。 我敢肯定我做的那部分是对的,但是我认为那是给我一个问题。

因此,在解析输入后,我将创建一个子进程以使用execvp系统调用执行参数。 在我的父进程中,我有一条条件语句,如果命令的最后一部分中有“&”号,则会调用Wait()函数。

所以我面临的问题是,当我执行此代码时,我能够正确执行第一个命令,但是无论第二个命令是什么,我都会遇到错误。 我认为这与事后不清除阵列有关,但是很难缩小此问题的范围。 任何帮助,将不胜感激。

#include <stdio.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <cstring>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdlib.h>

#define MAX_LINE 80 //the maximum length command

using namespace std;

int main()
{
  char* args[MAX_LINE/2 + 1]; //command line arguments
  char str[41]; //intitialize string for input
  int should_run = 1; //flag to determine when to exit program
  int index = 0;
  pid_t pid; //process id

  while (should_run) {
    cout << "prompt> ";
    fflush(stdout);

    cin.getline(str, 41);

    args[index] = strtok(str, " ");

    while (args[index] != NULL) {
      // test      cout << args[index] << endl;
      index++;
      args[index] = strtok(NULL, " ");
    }

    args[index + 1] = NULL;

    if (strcmp (args[0], "exit") == 0) //in input is "exit", exit the while loop
      break;

    // (1) fork a child process using fork()
    pid = fork();

    if (pid < 0) { //error handling
      perror("Fork Failed.");
      break;
    }
    // (2) the child process will invoke execvp()
    if (pid == 0) {
      //child process
      cout << "child:" << pid << endl;
      execvp (args[0], args);
    }

    // (3) if command didn't included &, parent will invoke wait()
    //parent process
    if (pid > 0)
      {
        // parent process
        if (strcmp (args[index], "&") == 0) {
          wait(0);
          cout << "parent: " << pid << endl;
        }
      }
  }
  return 0;
}

解析第二条及后续命令时,您忘记将index重新初始化为0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM