c - C 中的系统调用(文件描述符)

标签 c operating-system system-calls

以下代码已编写,用于在 Linux 中使用 sysyem 调用打开文件并将数据写入终端。

要读取文件描述符(fd)的值,它应该分配一个值。正如我们在 if else 语句中知道的那样,从 if 部分 else 部分或 else if 部分一次将执行一个部分。因此,根据以下代码,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);
        }        
    }

最佳答案

这里发生以下情况:

假设程序是在命令行上使用 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);
}

关于c - C 中的系统调用(文件描述符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851240/

相关文章:

c - 使用 C libcurl 库登录 Twitter

C - 用低位宏显示字符串

c - 重新分配 double 组

c - 字符驱动程序中的手动 sleep 会永远停止 read()

c - 添加到 Linux 的系统调用的历史?

c - Linux 系统调用和 errno

linux - Hook 系统调用ubuntu

c++ - 在 C 中工作,但在 C++ 中不工作

windows - 在进程开始之前将 dll 注入(inject)进程的优雅方法

memory-management - 如果CPU正在处理相应的内存请求,如何保证内存页面不会被驱逐?