父子进程同时写文件

yphui18 2011-07-05 02:16:49
6 int main (void)
7 {
8 FILE* file;
9 file=fopen("a.txt","a");
10 perror("fopen ");
11 char txt[100];
12 pid_t pid=fork();
13 if(pid<0)
14 {
15 perror("create thread error:");
16 }
17 else if(pid==0)
18 {
19 printf("child begin\n");
20 int i=0;
21 for(i=0;i<5;i++)
22 {
23 fputs("a",file);
24 printf("child\n");
25 sleep(1);
26 }
27 }
28 else if(pid>0)
29 {
30 printf("father begin\n");
31 int j=0;
32 for(j=0;j<5;j++)
33 {
34 fputs("b",file);
35 printf("father\n");
36 sleep(1);
37 }
38
39 }
40 exit(0);
41
42 }
运行后,打印出来的信息是
fopen : Error 0
child begin
child
father begin
father
child
father
child
father
child
father
child
father
但是a.txt的内容是
aaaaabbbbb

请问高手,a.txt的内容为什么不是ababababab,要怎么样才能实现ababababab的效果
...全文
165 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
luciferisnotsatan 2011-07-05
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 dizuo 的回复:]

引用 1 楼 bdmh 的回复:
创建了新的进程,但没有进行互斥,导致访问随机

aaaaabbbbb就是互斥的结果。。。
[/Quote]
lz代码里压根没加锁。。。
由于没fflush,数据可能还在缓冲区里,没写到文本里。
至善者善之敌 2011-07-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bdmh 的回复:]
创建了新的进程,但没有进行互斥,导致访问随机
[/Quote]

+++1
yphui18 2011-07-05
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
按照2楼的讲法,在每个 fputs 后调用一次 fflush(file); 这样试了是ababababab,假设这时再加了
fflush(file); 这行程序后,希望实现互斥,也就是想出现aaaaabbbbb的结果,那要怎么加锁?
char buf[900000];
int main (void)
{
FILE* file;
file=fopen("a.txt","a");
perror("fopen ");
char txt[100];


pid_t pid=fork();
if(pid<0)
{
perror("create thread error:");
}
else if(pid==0)
{


printf("child begin\n");
int i=0;
for(i=0;i<5;i++)
{
fputs("a",file);
printf("child\n");
fflush(file);
sleep(1);
}

}
else if(pid>0)
{


printf("father begin\n");
int j=0;
for(j=0;j<5;j++)
{
fputs("b",file);
printf("father\n");
fflush(file);
sleep(1);
}


}
exit(0);

}

赵4老师 2011-07-05
  • 打赏
  • 举报
回复
如果不是ababababab,参考跨进程锁。
ryfdizuo 2011-07-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 bdmh 的回复:]
创建了新的进程,但没有进行互斥,导致访问随机
[/Quote]
aaaaabbbbb就是互斥的结果。。。
赵4老师 2011-07-05
  • 打赏
  • 举报
回复
int main (void)
{
FILE* file;
char txt[100];
pid_t pid=fork();
if(pid<0) {
perror("create thread error:");
} else if(pid==0) {
printf("child begin\n");
int i=0;
for(i=0;i<5;i++) {
file=fopen("a.txt","a");
fputs("a",file);
fclose(file);
printf("child\n");
sleep(1);
}
} else if(pid>0) {
printf("father begin\n");
int j=0;
for(j=0;j<5;j++) {
file=fopen("a.txt","a");
fputs("b",file);
fclose(file);
printf("father\n");
sleep(1);
}

}
exit(0);

}

www_adintr_com 2011-07-05
  • 打赏
  • 举报
回复
文件指针里面实现了缓存的.
在每个 fputs 后调用一次 fflush(file); 就可以得到你想要的结果了.
bdmh 2011-07-05
  • 打赏
  • 举报
回复
创建了新的进程,但没有进行互斥,导致访问随机

64,654

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧