c - 无法使用 write() 写入标准输出
问题描述
我正在尝试使用 write() 一次将一个字符写入标准输出一个字节。该程序编译并运行良好,但输出结果并不完全正确。现在我试图让它通过 write 运行,但我没有在控制台中得到任何输出。
void myfunction(char *s, int fd, int n){
for(int i = 0; i != sizeof(s) - 1; ++i){
fprintf(stderr, "%s\n", &s[i]); // This correctly prints out the string
if( write(fd, &s, 1) < 0){ // This will not print to the console
perror("Error: Write problems."); // Have not gotten any errors yet
}
wastesometime(n); // This just calls a for loop that runs n times
}
}
sizeN = sprintf(buffer, "This is process %d with ID %ld and parent id %ld\n", i, (long)getpid(), (long)getppid());
myfunction(buffer, STDOUT_FILENO, n);
目前我正在从 fprintf 以这种形式获得输出:
process 2 with ID 27711 and parent id 27710
rocess 2 with ID 27711 and parent id 27710
ocess 2 with ID 27711 and parent id 27710
cess 2 with ID 27711 and parent id 27710
ess 2 with ID 27711 and parent id 27710
ss 2 with ID 27711 and parent id 27710
s 2 with ID 27711 and parent id 27710
2 with ID 27711 and parent id 27710
2 with ID 27711 and parent id 27710
with ID 27711 and parent id 27710
with ID 27711 and parent id 27710
ith ID 27711 and parent id 27710
th ID 27711 and parent id 27710
h ID 27711 and parent id 27710
ID 27711 and parent id 27710
ID 27711 and parent id 27710
D 27711 and parent id 27710
27711 and parent id 27710
27711 and parent id 27710
7711 and parent id 27710
711 and parent id 27710
11 and parent id 27710
1 and parent id 27710
and parent id 27710
and parent id 27710
nd parent id 27710
d parent id 27710
parent id 27710
parent id 27710
arent id 27710
rent id 27710
ent id 27710
nt id 27710
t id 27710
id 27710
id 27710
d 27710
27710
27710
7710
710
10
0
但我试图为每个进程使用 write 而不是 fprintf 来获取此输出:
This is process 2 with ID 27711 and parent id 27710
这可能是相关的,但fprintf(stderr, %d\n", &s[i])
有效并且fprintf(stdout, %d\n", &s[i])
?我相信stderr
优先,但我不认为其他输出根本不会被打印?
是的,我已经进行了一些研究,但我发现大多数答案都是有用fwrite()
的或在 C++ 中,因此不是我想要的。
解决方案
void myfunction(char *s, int fd, int n)
{
for (int i = 0; i < strlen(s); i++)
{
if (write(fd, s + i, 1) < 0)
{
perror("Error: Write problems.");
}
sleep(n);
}
}
你不需要发送 &s 来写,因为 s 已经是一个指针,已经包含一个地址......发送 &s 就像发送一个地址的地址......另外,不要忘记在你的循环,否则您将一遍又一遍地写相同的字符。
当您使用 printf(或其任何变体)时,您可以使用 %c 打印一个字符,您可以使用 %s 打印一个字符串(char *)
推荐阅读
- java - 在 Spring Boot 中捕获 JDBCConnectionExceptions
- ios - 如何在 Xcode 配置文件中获取嵌套值?
- sql - 如何在 Athena (Presto) 中查询和迭代结构数组?
- katalon-studio - Katalon - 如何访问表中的元素?
- node.js - 续集如何转换对象列表
- angular - 如何使用 Angular 7 制作凝乳
- c++ - 如何在无捕获的lambda,C ++中初始化范围内的项目
- php - 静态页面中博客文章的标题
- express - 添加和检索音频
- oracle - ORACLE - 如果存在则更新表,否则插入使用 rownum 匹配