首页 > 解决方案 > 为什么这不删除用户命令末尾的“&”?

问题描述

我正在用 C 编写一个基本的 shell,如果输入的命令包含 &,那么它将在后台运行并且用户仍然可以执行其他命令。

但由于某种原因,我可以让程序在后台运行,所以我知道 IF 语句有效(它检查'&')但我不能让它从命令。

以下是相关代码,欢迎提问:

int main(void)
{
  Command cmd;
  int n;

  while (!done) {

    char *line;
    line = readline("> ");
//This should check if 'line' contains an &, and remove it if so.
    if (strchr(line, "&") != NULL) {
      line[strlen(line) - 1] = '\0';
      char **cmds;
      cmds = separateCmd(line);

      if (!line) {
      /* Encountered EOF at top level */
        done = 1;
      } else {
        stripwhite(line);

        if(*line) {
          add_history(line);
          /* execute it */
          n = parse(line, &cmd);
          PrintCommand(n, &cmd);
          executeBgCmd(cmds);
        }
      }

        if(line) {
          free(line);
        }
    } else {
      char **cmds;
      cmds = separateCmd(line);

      if (!line) {
      /* Encountered EOF at top level */
        done = 1;
      } else {
        stripwhite(line);

        if(*line) {
          add_history(line);
          /* execute it */
          n = parse(line, &cmd);
          PrintCommand(n, &cmd);
          executeCmd(cmds);
        }
      }

      if(line) {
        free(line);
      }
    }
  }
  return 0;
}

任何帮助将非常感激。提前谢谢你:D

标签: carraysstringcharstrlen

解决方案


当我编译您的代码并查看我看到的警告时:

warning: passing argument 2 of ‘strchr’ makes integer from pointer without a cast [-Wint-conversion]

所以编译器告诉我你的代码是错误的!查找strchr(例如http://man7.org/linux/man-pages/man3/strchr.3.html),我看到strchr期望第二个参数是要搜索的字符。但是您的代码传递了一个字符串(或更准确地说:指向字符串第一个字符的指针):

if (strchr(line, "&") != NULL) {
                 ^^^
                 ups

试试这个

if (strchr(line, '&') != NULL) {

从手册页中,我还可以看到strchr如果找到它,它会返回一个指向该字符的指针。因此,编写如下代码可能是有意义的:

char* pHit = strchr(line, '&');
if (pHit != NULL) {
  *pHit = '\0';      // Terminate string at first &
}

所以&不必是最后一个字符。

一个简单的测试程序可以是:

int main()
{
    char line[] = "hello & world";
    printf("Before: %s\n", line);
    char* pHit = strchr(line, '&');
    if (pHit != NULL) {
      *pHit = '\0';
    }
    printf("After: %s\n", line);

    return 0;
}

输出:

Before: hello & world
After: hello

推荐阅读