- 论坛徽章:
- 0
|
一个程序有多个进程,父子进程都以O_APPEND方式打开同一个日志文件,用系统调用write向文件写入一条日志,像这种没有进程间相互协调,会不会出现日志信息混乱的情况(一个进程的日志写入一半后出现另一进程的日志)。
写了个小程序测试了一下,很简单的两个进程,大家看看,这个程序没有出现信息混乱的情况。可能因为写入的信息太少,没有发生在日志写到一半的时候出现进程间切换。
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <fcntl.h>
- int main(int argc,char * argv[])
- {
- int fd;
- int childpid;
- int i;
- char buf[1024];
- for(i=0 ;i<1; i++){
- if(childpid = fork())
- break;
- }
- if(childpid == -1){
- perror("failed to fork\n");
- return 1;
- }
- fd = open("tmp.dat",O_WRONLY|O_CREAT|O_APPEND,0666);
- if(fd < 0){
- perror("failed to open\n");
- return 1;
- }
- if(childpid > 0){
- memset(buf,0,1024);
- strcpy(buf,"1111111111111111111111111111111111111111111111111111111111111111111111111111111111
- 1111111111111111111111111111111111111111111111111111111");
- strcat(buf,"\n");
- for(i=0; i<100000; i++){
- usleep(1000);
- write(fd,buf,strlen(buf));
- }
- }else{
- memset(buf,0,1024);
- strcpy(buf,"2222222222222222222222222222222222222222222222222222222222222222222222222222222222
- 222222222222222222222222222222222222222222222222222222");
- strcat(buf,"\n");
- for(i=0; i<100000; i++){
- usleep(1000);
- write(fd,buf,strlen(buf));
- }
- }
- close(fd);
- return 0;
- }
复制代码
[ 本帖最后由 linuxiang 于 2006-8-3 23:46 编辑 ] |
|