无法使用write()写入标准输出

时间:2018-05-22 23:20:10

标签: c unix posix

我正在尝试使用write()将char写入标准输出一次一个字节。该程序编译并运行正常,但输出结果不是很正确。现在我试图让它与write一起运行,但我没有在控制台中获得任何输出。

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

目前我正在以fprintf:

的形式获得输出
This is process 2 with ID 27711 and parent id 27710   

但我想尝试使用write而不是fprintf为每个进程获取此输出:

fprintf(stderr, %d\n", &s[i])

这可能相关,但fprintf(stdout, %d\n", &s[i])有效且stderr?我相信fwrite()优先考虑,但我不认为其他输出根本不会被打印出来?

是的,我做了一些研究,但大多数答案我发现使用while(boolean_1 == false)或者使用C ++,因此不是我想要的。

2 个答案:

答案 0 :(得分:1)

缺少一些细节,但根据您目前发布的内容,这应该有效:

void myfunction(char *s, int fd, int n) {

    if( write(fd, s, strlen(s)) < 0) {
         perror("Error: Write problems.");
    }

    wastesometime(n);
}

让我们确保我们了解这里发生了什么。在myfunction内,参数s是指向char的指针,更具体地说,它指向以空字符结尾的字符数组的第一个字符,这是C对字符串的定义

您尝试使用的write函数也接受指向char的指针。但是,它并不坚持(或期望)指针专门针对以null结尾的字符串;它可以是指向任何字符数组的指针。由于write不假设以空字符结尾的字符串,因此您必须准确地告诉它要写入多少字符。

由于你是以一个以空字符结尾的字符串开头的,你可以通过调用它来计算字符串中的实际字符数(这正是你需要作为第三个参数传递给write的数字)。标准strlen函数,如我所示。

您的问题可能与STDOUT_FILENO未正确定义有关。请尝试所有这四个电话:

myfunction(buffer, 1, n);

myfunction(buffer, 2, n);

myfunction(buffer, fileno(stdout), n);

printf("STDOUT_FILENO = %d\n", STDOUT_FILENO);

答案 1 :(得分:1)

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已经是一个指针,已经包含一个地址......而发送&amp; s就像发送一个地址的地址......而且,不要忘记在循环中递增该地址,或者你会反复写出相同的字符。

使用printf(或其任何变体)时,可以使用%c打印字符,使用%s打印字符串(char *)