要求是用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
研究了一天都没有结果
请高手帮我看看到底问题出在哪里?谢谢!
附件里的是代码
同时贴在这里:
#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);
}
}
}
}