【问题标题】:unix goto command source codeunix goto 命令源代码
【发布时间】:2014-12-31 17:15:08
【问题描述】:

这是一个历史悠久的 Unix goto.c 的源代码:http://v6shell.org/history/goto.c

所以我们试图找到一个记录“goto label”调用的匹配标签。

我的问题:

if (getlin(line)) {
        write(1, "label not found\n", 16);
        return;
        }

所以我希望如果 getlin() 返回 true,我们应该打印出“未找到标签”并退出程序。

但是看看这个:

getlin(s)
char s[];
{
    int ch, i;

    i = 0;
l:
    if ((ch=getc())=='\0') return(1);
    if (ch!=':') {
        while(ch!='\n' && ch!='\0')
            ch = getc();
        goto l;
        }
    while ((ch=getc())==' ');
    while (ch!=' ' && ch!='\n' && ch!='\0') {
        s[i++] = ch;
        ch = getc();
        }
    while(ch != '\n')
        ch = getc();
    s[i] = '\0';
    return(0);
}

如果我们找到标签,getlin() 将返回 0(true),如果没有找到,则返回 1(false)。

但它应该是相反的,否则我们需要说:

if (**!** getlin(line)){}

这里有什么问题?

【问题讨论】:

  • 不确定这是怎么回事,但作为一般经验法则:unix 实用程序传统上返回 0(零)表示成功,其他一切都表示错误(错误代码)。所以我说函数实现是有道理的,条件是有问题的。
  • 是的,这就是问题所在。但它有效,那为什么有效呢?

标签: c shell unix


【解决方案1】:

0C 中被视为false。因此混乱。您可以通过运行这个小示例代码来尝试:

#include <stdio.h>

int i = 0;

int main() {
  if(i) {
    printf("i is %d and it is true\n", i);
  } else {
    printf("i is %d and it is false\n", i);
  }
  return 0;
}

作为退出代码,0 被视为成功。但在条件句中(C),0 的计算结果为 false1 的计算结果为 true

但是,在 bash 中,0 被认为是 true,即使在条件句中也是如此。这是因为在大多数 bash 用例中,这种方式更方便,因为我们总是在处理进程。

【讨论】:

    猜你喜欢
    • 2010-10-27
    • 1970-01-01
    • 2019-01-26
    • 2021-12-07
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 2010-09-06
    相关资源
    最近更新 更多