根据glibc的文档,如果数据小于PIPE_BUF,则对管道的写入是原子的。 posix pipe as a work queue
但是:如果发生信号,写入可能会中断。让我们假设,#include <stdio.h>
#include <stdlib.h>
void printAfterX(int* arr, size_t size, size_t offset);
int main(void)
{
int arr[] = { 4, 8, 6, 2, 1, 3, 5, 7, 8, 9, 5 };
printAfterX(arr, 11, 7);
system("PAUSE");
return 0;
}
void printAfterX(int* arr, size_t size, size_t offset)
{
if (offset >= size)
{
printf("not found");
return;
}
else
{
while(offset < size)
{
printf("%d ", *(arr + offset));
offset++;
}
}
}
被阻止,因为管道几乎已满。现在出现了一个信号。该数据是否会以原子方式写入管道?
write
答案 0 :(得分:1)
Atomic只是意味着 "the whole amount written in one operation is not interleaved with data from any other process."
信号中断略有不同。根据{{3}},管道是一个慢速设备&#34;。因此,除非设置了SA_RESTART
,否则write
操作将返回成功并写入数据。因此,最好始终检查write的返回值,以确保所有数据都已写入。或者,您可以屏蔽可能的信号。