【问题标题】:System calls in C (File Descriptor)C中的系统调用(文件描述符)
【发布时间】:2017-02-12 13:22:12
【问题描述】:

以下代码已编写为使用 linux 中的 sysyem 调用打开文件并将数据写入终端。

要读取文件描述符 (fd) 的值,它应该分配一个值。正如我们在 if else 语句中所知道的,从 if part else part 或 else if part 部分将一次执行。因此,根据以下代码 fd 将仅在 else if 行有一个值。但是当我传递一个文件名并运行这个程序时,它会打开文件。文件打开是在 read(() 系统调用的 while 循环中发生的。但是 while 循环在 else 部分,因为文件描述符理论上不能有任何值。那么 read 函数如何准确识别文件?这让我很困惑.

    #include <stdio.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <unistd.h>

    #define SIZE 10

    int main(int argc, char *argv[])
    {
        int fd,n;
        char buff[SIZE];

        if(argc != 2)
        {
            printf("USAGE : %s\n",argv[0] );
            exit(1);        
        }        
        else if ((fd = open(argv[1],0)) == -1)
        {
            perror("STATUS");
            exit(1);
        }
        else
        {
            while((n = read(fd,buff,SIZE)) > 0)
            {
                write(1,buff,SIZE);

            }
            close(fd);
        }        
    }

【问题讨论】:

  • else if ((fd = open(argv[1],0)) == -1) fd 具有从open 返回的值。这就是 C 中的工作方式。了解如何使用调试器并逐步完成程序,您就会明白。
  • 函数:read() 返回 ssize_t,而不是 int
  • 输出错误信息时,应该输出到stderr,而不是stdout。因此,建议您的错误消息类似于:fprintf( stderr, "USAGE : %s\n",argv[0] );
  • 当内容从不使用时,为什么还要设置(甚至拥有)变量n?建议更改此行:while((n = read(fd,buff,SIZE)) &gt; 0)while( read(fd,buff,SIZE) &gt; 0 )

标签: c operating-system system-calls


【解决方案1】:

以下发生在这里:

假设程序在命令行中以 xyz.txt 启动,并且假设 xyz.txt 文件确实存在:

if(argc != 2)
{
                                        // we don't get here because argc == 2
    printf("USAGE : %s\n",argv[0] );
    exit(1);
}
else if ((fd = open(argv[1],0)) == -1)  // the statement in the if clause will therefore
                                        // be executed, fd will be something different 
                                        // from -1 because open succeeded
{
    perror("STATUS");                   // therefore we dont ge here either
    exit(1);
}
else
{                                       // instead we get here and
    while((n = read(fd,buff,SIZE)) > 0) // everything works as expected
    {
        write(1,buff,SIZE);

    }
    close(fd);
}

【讨论】:

    猜你喜欢
    • 2014-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2011-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多