我花了几个小时来研究行为,首先是关于这些问题:
看来,如果在打开文件时使用'O_APPEND'标志,则在Linux上从多个进程登录到同一文件总是可以的。而且我相信python肯定会在其日志记录模块中使用'O_APPEND'标志。
并通过一个小测试:
#!/bin/env python
import os
import logging
logger = logging.getLogger('spam_application')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('spam.log')
logger.addHandler(fh)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
for i in xrange(10000):
p = os.getpid()
logger.debug('Log line number %s in %s', i, p)
Run Code Online (Sandbox Code Playgroud)
我用它运行:
./test.py & ./test.py & ./test.py & ./test.py &
Run Code Online (Sandbox Code Playgroud)
我发现spam.log中没有错。此行为可能支持上述结论。
但是问题来了:
最后,如果两个进程正在同一文件上执行写操作,那是指它们正在调用同一文件上的write(2),谁可以确保来自两个进程的数据不会交织(内核或文件系统?),以及如何交织。[注意:我只想深入了解写系统调用,对此的任何欢迎。
编辑1:
#include <unistd.h>
#include <stdio.h>
int main()
{
char buff[100];
int pfd[2];
buff[0] = '\0';
pipe(pfd);
if (fork())
write(pfd[1],"hello world", 12);
fork();
read(pfd[0], buff, 100);
printf("%s\n", buff);
printf("goodbye\n");
}
Run Code Online (Sandbox Code Playgroud)
我知道只有一个进程会写入管道,但我不明白的是,一个进程是否有可能从管道中读取数据并仅读取“hello world”的一部分,而其他进程读取其他部分“你好世界”?
换句话说,当一个进程尝试读取管道而另一个进程正在读取它时会发生什么?