执行命令的 C 程序因 sleep

问题描述

我写了一个程序,它逐行读取 bash 文件并执行里面写的命令。

好像正常执行标准命令(虽然终端没有输出),但是读取sleep命令的时候报错:

sleep 3: missing operand
Try 'sleep 3 --help' for more @R_77_4045@ion.
char** string_separator(char* string,const char a_delim)
{
    char** result    = 0;
    size_t count     = 0;
    char* tmp       = string;
    char* last_dot = 0;
    char delimiter[2];
    delimiter[0] = a_delim;
    delimiter[1] = 0;


    while (*tmp)
    {
        if (a_delim == *tmp)
        {
            count++;
            last_dot = tmp;
        }
        tmp++;
    }

    count += last_dot < (string + strlen(string) - 1);
    count++;
    result = malloc(sizeof(char*) * count);

    if (result)
    {
        size_t idx  = 0;
        char* token = strtok(string,delimiter);

        while (token)
        {
            assert(idx < count);
            *(result + idx++) = strdup(token);
            token = strtok(0,delimiter);
        }
        assert(idx == count - 1);
        *(result + idx) = 0;
    }

    return result;
}

int main(int argc,char *argv[]) {

for (int i = 1; i < argc; i++) {
  FILE * fp;
  fp = fopen(argv[i],"r");
  char buf[100];
  int bytes_read = 0;
  char * inputcopy = malloc(255 * sizeof(char));
  const char delim[] = " ";

  while (fgets(buf,sizeof buf,fp) != NULL) {

    if (strstr(buffer,"#!/")) {

    } else {
      char ** strtoken = string_separator(buf,'\n');
      char * firstWord = getFirstWord(buf,inputcopy,delim);
      pid_t pid;
      pid = fork();

      if (pid == 0) {
        execvpe(firstWord,strtoken,NULL);
        exit(1);
      } else {

        int status;
        waitpid(pid,& status,0);
      }

    }
  }
}

return 0;

}

为什么程序不能使用 sleep 命令?

编辑:在代码中进行了函数定义和缩进等修改,我认为问题可能出在 string_separator 函数上,它可能无法按预期将字符串拆分为字符数组。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)