c - 编译中的 write() 警告消息

标签 c warnings

我有一段代码来创建从输入参数打印消息的函数。

我一直在使用 c9.io 编译代码并且工作得很好,没有警告,但是当我在本地执行它时,它会显示如下警告:

child2bok: c39:11: warning: Ignoring return value of 'write', declares with attribute warn_unused_result [-Wunused -result]

这就是代码。当然这是 write() 定义的问题,但我对 unix 编程很新手,不知道解决它。它执行得很好,但我想在交付给老师之前删除警告。

这是代码:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/time.h>
#include <unistd.h>

#include "rutines.h"

void children();
void show_help();

int main(int argc, char *argv[])
{
    int ord;

    if (argc > 1)
        ord = atoi(argv[1]);
    if (argc == 1)
    {
        show_help("Error"); 
        exit(1);
    }

    children(ord);
}

void children(int ord)
{
    char msg[10];

    srand(getpid());
    sleep(rand() % 5);
    sprintf(msg, " %d", ord);
    while (strlen(msg) > 0)
    {
    int written= write(1, msg, strlen(msg));
    if (written < 0)
    break;

    exit(0);
}

void show_help(char *err_message)
{
    write_string(err_message,"");
    write_string("Usage: child2aok \n","");
}

最佳答案

您应该检查并处理 write() 命令返回的值。来自 write 文档:

write [...] may return less than count even under valid conditions.

为什么不简单地使用 printf("%d", ord); 而不是 sprintf(msg, "%d", ord);写(1,消息,strlen(消息))

关于c - 编译中的 write() 警告消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20601217/

相关文章:

java - 从 HTTPS 重定向到第 3 方 HTTP 页面,没有证书错误

c++ - 未知来源的警告 : "can' t find linker symbol for virtual table for. .."

angular - 我如何解决这个 Angular 7 "Circular dependency detected"警告

c - (C) Scanf - 输入每次都为 0

c - 我应该相信 C 中的短通常是 2 个字节吗?

c - 使用 %c 奇数循环不起作用

c++ - C/C++ 中的 Aho-Corasick 算法(十六进制)

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

ruby - 为什么没有赋值运算符允许我在没有编译器警告的情况下修改 Ruby 常量?

c - 这段代码是如何工作的,这是一个好的做法吗?