我有一段代码来创建从输入参数打印消息的函数。
我一直在使用 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/