使用 Write 系统调用不间断打印 Int 数组

Uninterupted Printing Of Int Array Using Write System Call

我的主程序正在创建多个子程序,每个子程序都写入标准输出。为了避免它们互相覆盖,我使用了 sprintf 写入组合,如下所示:

sprintf(buf, "Bubble Sort Process Started\n");
write(0, &buf, strlen(buf)); 

当我尝试打印出一个 int 数组时,我 运行 遇到了问题。每次程序 运行s 时数组的大小都会改变,所以我不能让一组 sprintf 一次打印所有内容。我能想到的唯一打印它的方法是使用循环遍历数组,但是其他进程可以让它们的输出出现在中途。如何在不让另一个进程同时打印其输出的情况下打印整个数组?

假设你在一个 POSIX 系统上(你可能是,从你假设有一个 write 系统调用来判断),你应该能够为 filedescriptor 1 设置一个锁在你开始你的写调用之前,并在你完成你的 write 批处理后解锁它。

下面是一个演示它的简单程序:

#include <unistd.h>
#include <fcntl.h>

void print(char C)
{
    for(;;){
#if LOCK
        fcntl(1, F_SETLKW, &(struct flock){ F_WRLCK, SEEK_SET, 0, 1 });
#endif
        for(int i=0; i<100; i++)
            write(1, &C, 1);
        write(1, "\n", 1);
#if LOCK
        fcntl(1, F_SETLKW, &(struct flock){ F_UNLCK, SEEK_SET, 0, 1 });
#endif
    }
}
int main()
{
    for(int i=0; i<4; i++) /*4 children*/
        if(0==fork())
            print('a'+i);
    pause(); /*terminate it with Ctrl+C*/

}

这个程序将创建 4 个 children,每个尝试打印无限系列的行,其中每行包含 100 个字符 C(第一个 'a' child, 'b' 第二个,依此类推)。由于一次写入 1 个字节,因此这些行将交织在一起。编译时加上-DLOCK=1,输出的每一行都不会被打断。