| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 516 人关注过本帖
标题:[求助]一个c编程作业的问题,关于多进程同步
只看楼主 加入收藏
coolish
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2007-3-4
收藏
 问题点数:0 回复次数:0 
[求助]一个c编程作业的问题,关于多进程同步

要求是用3个进程输出
P3, line 1, ghi
P2, line 1, def
P1, line 1, abc
P3, line 2, ghi
P2, line 2, def
P1, line 2, abc

P3, line 30, ghi
P2, line 30, def
P1, line 30, abc
三个进程分别对应输出P3,P2,和P1开头的行
因为没学进程间通信,所以要求这三个进程用读写同一个文件的方法来保持同步
ghi,def,abc是程序执行的三个参数
我写的程序,用gcc编译后运行,输出了第一行P3,Line 1,xxx 以后会显示segmentation fault
研究了一天都没有结果
请高手帮我看看到底问题出在哪里?谢谢!
附件里的是代码

3lNci92H.zip (1.11 KB) [求助]一个c编程作业的问题,关于多进程同步



同时贴在这里:

#include<stdio.h>
#define FILENAME "sync.txt"
#include<stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc , char** argv)
{
// argc means argunment counter , argv means argrunment value
// char** means "pointer to pointer to char". As we can treat char* as "character string", so char** is array of character string.
//
int i;
int pid,p2pid,p1pid,p3pid;
FILE* file;
int value=3;
p1pid=getpid();
if ( ( file = fopen(FILENAME,"wb") )== NULL )
{
printf("Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fwrite(&value, sizeof(int),1,file);
fclose(file);
pid=fork();
if (p2pid < 0 )
{
printf("Fork error , exit now \n");
exit(0);
}
if(pid==0)
{
p2pid=getpid();
pid=fork();
}
if(pid==0) p3pid=getpid();
for (i=1;i<31;i++)
{
while(1)
{
if (getpid()==p1pid)
{
if ( ( file = fopen(FILENAME,"rb") )== NULL )
{
printf("P1 Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fread(&value,sizeof(int),1,file);
fclose(file);
if (value==1)
{
printf("P1,Line %d,%s\n",i,argv[1]);
value=3;
if ( ( file = fopen(FILENAME,"wb") )== NULL )
{
printf("p2 Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fwrite(&value,sizeof(int),1,file);
fclose(file);
break;
}
else fclose(file);
}
if (getpid()==p2pid)
{
if ( ( file = fopen(FILENAME,"rb") )== NULL )
{
printf("p2 Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fread(&value,sizeof(int),1,file);
fclose(file);
if (value==2)
{
printf("P2,Line %d,%s\n",i,argv[2]);
value=1;
if ( ( file = fopen(FILENAME,"wb") )== NULL )
{
printf("p2 Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fwrite(&value,sizeof(int),1,file);
fclose(file);
break;
}
else fclose(file);
}

if (getpid()==p3pid)
{
if ( ( file = fopen(FILENAME,"rb") )== NULL )
{
printf("p3 Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fread(&value,sizeof(int),1,file);
fclose(file);
if (value==3)
{
printf("P3,Line %d,%s\n",i,argv[3]);
value=2;
if ( ( file = fopen(FILENAME,"wb") )== NULL )
{
printf("p2 Cannot open file \"%s\"\n",FILENAME);
exit(0);
}
fwrite(&value, sizeof(int) , 1 , file);
fclose(file);
break;
}
else fclose(file);
}
}

}

}


搜索更多相关主题的帖子: 作业 进程 
2007-03-04 00:33
快速回复:[求助]一个c编程作业的问题,关于多进程同步
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.022462 second(s), 10 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved