我想用Pascal编写的两个独立程序使用附加文本文件在它们之间进行通信。它适用于前2-3条消息,但随后它会在sender.pas或receiver.pas中发出运行时错误你知道我的错误在哪里或你有什么建议吗?
第一个程序receiver.pas
var
f : text;
s : string;
begin
{I-}
Assign(f,'main.in');
while true do
begin
reset(f);
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by sender
reset(f); //
end; //
if eof(f) then
close(f)
else
begin
readln(f,s);
close(f);
rewrite(f);
close(f);
writeln(s);
end;
end;
{I+}
end.
第二个程序sender.pas
var
f : text;
s : string;
begin
{I-}
Assign(f,'main.in');
while true do
begin
readln(s);
rewrite(f); //
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by receiver
rewrite(f); //
end; //
writeln(f,s);
close(f);
end;
{I+}
end.
答案 0 :(得分:2)
我注意到的一些事情:
这是什么编译器? Delphi,免费Pascal?哪个版本?
我的新(免费Pascal)接收器代码变为:
uses sysutils;
var
f : text;
s : string;
begin
filemode := 2; // read-only
{$I-}
Assign(f,'main.in');
while true do
begin
reset(f);
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by sender
sleep(1000);
reset(f);
end;
if eof(f) then
begin
close(f);
sleep(1000);
end
else
begin
readln(f,s);
close(f);
rewrite(f);
close(f);
writeln(s);
end;
end;
{$I+}
end.
新的发件人代码是:
uses sysutils;
var
f : text;
s : string;
begin
filemode := 2; // read-only
{$I-}
Assign(f,'main.in');
while true do
begin
reset(f);
while IOResult<>0 do //
begin // Wait until the file
close(f); // is closed by sender
sleep(1000);
reset(f);
end;
if eof(f) then
begin
close(f);
sleep(1000);
end
else
begin
readln(f,s);
close(f);
rewrite(f);
close(f);
writeln(s);
end;
end;
{$I+}
end.
答案 1 :(得分:1)
一些事情:确保在每次文件操作后检查IOResult,而不仅仅是重写/重置 - 如果你的重置/重写失败,请不要调用close - 你可能想要在那些重试中使用Sleep(250)之类的东西环路。