c - 参数不能为负(函数 : open)

标签 c file-io

我编写函数来防止运行具有相同配置(fifo 文件)的两个应用程序实例:

if( !filename_specified ) {
    char *fifofile = get_fifo_filename( config_get_uid( ct ) );
    int fifofd;

    if( !fifofile ) {
        lfprintf( stderr, _("%s: Cannot allocate memory.\n"), argv[ 0 ] );
        return 0;
    }

    /* negative_return_fn: Function "open(fifofile, 2049)" returns a negative number */
    fifofd = open( fifofile, O_WRONLY | O_NONBLOCK );
    if( fifofd >= 0 ) {
        lfprintf( stderr, _("Cannot run two instances of application with the same configuration.\n") );
        close( fifofd );
        return 0;
    }
    /* negative_returns: "fifofd" is passed to a parameter that cannot be negative */
    close( fifofd );
}

我的代码收到此警告:

负值用作期望正值的函数的参数。

最佳答案

如果 open() 返回一个失败的负值。如果open()失败返回的值不是有效的文件描述符,文件尚未打开,所以它不需要不能是close()编辑。

通过只传递 fifofd 来解决这个问题至 close()如果它大于或等于 0 , 也就是对 open() 的对应调用成功:

if (0 <= fifofd)
{
  if (-1 == close(fifofd))
  {
    perror("close() failed");
  }
}

关于c - 参数不能为负(函数 : open),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830367/

相关文章:

c++ - 优化文件打开和读取

创建循环链接列表编译器停止工作

c - 而对于 : what is the best?

c - getopt 无法识别 c 中的多个命令行标志

c - 编写新的系统调用

c - 为结构中的二维数组赋值是段错误

java - 将来使用 NIO 和 NIO2 处理文件和文件系统 : Before NIO,

matrix - 读取并覆盖同一个文件

c - 使用 C 中的线程写入全局文件

c - 如何在 C 函数中使用二维数组作为输出参数