I did exercise with a problem of OS book. I have a difficulty with implementing shared memory between two processes. work procedure is following.
one process(A) starts another process(B). and that one, another process(B), do its job - called collatz conjecture (it is just a iterative work.). To share B's job, B has to write his work into stream.
below is my source code(A).
namespace collatz_conjecture
{
class colltz_conjecture
{
static void Main(string[] args)
{
Console.WriteLine("===== Start Process =====");
MemoryMappedFile mmf = MemoryMappedFile.CreateNew("test", (long)1e5 );
Process child = new Process();
child.StartInfo.FileName = "child.exe";
child.Start();
child.WaitForExit();
using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, (long)1e5))
{
StreamReader sr = new StreamReader(stream);
Console.WriteLine(sr.ReadLine());
Console.WriteLine("===== End of Process =====");
}
}
}
}
and the below is source coude B.
namespace child
{
class child
{
static void Main(string[] args)
{
Console.WriteLine("임의의 정수를 입력해주세요");
int n =Convert.ToInt32(Console.ReadLine());
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("test",MemoryMappedFileRights.Write))
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, (long)1e2))
{
StreamWriter sw = new StreamWriter(stream);
while (true)
{
sw.Write(n + " " );
Console.Write(n + " ");
if (n == 1) break;
if (n % 2 == 0) n /= 2;
else n = 3 * n + 1;
Thread.Sleep(500);
}
Console.WriteLine();
}
}
}
catch
{
while (true)
{
Console.Write("WHY IT DOESNT WORK????\n");
Thread.Sleep(500);
};
}
}
}
}
I think I did what i can do at that time. I copied msdn's source msdn's example, and pasted into my source. It worked correctly.
but with my source, A just print out null string..
is It banned use streamReader in MemoryMappedFile? or what is the problem
picture of two console, left one is A right one is B.
Solved. The matter is about the.... "StreamWriter". I'm really sorry that It is not the IPC one. I figured out that StreamWriter should follow Close or flush. So I added "sw.Flush()"
static void Main(string[] args)
{
Console.WriteLine("임의의 정수를 입력해주세요");
int n =Convert.ToInt32(Console.ReadLine());
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.OpenExisting("test",MemoryMappedFileRights.Write))
{
using (MemoryMappedViewStream stream = mmf.CreateViewStream(0, (long)1e2))
{
StreamWriter sw = new StreamWriter(stream);
while (true)
{
sw.Write(n + " " );
Console.Write(n + " ");
if (n == 1) break;
if (n % 2 == 0) n /= 2;
else n = 3 * n + 1;
Thread.Sleep(500);
}
sw.Flush(); // <---- added
Console.WriteLine();
}
}
}
catch
{
while (true)
{
Console.Write("WHY IT DOESNT WORK????\n");
Thread.Sleep(500);
};
}
}
and It works well..
sorry. I think my ask was not good enough to post. but I hope my ask, answer will help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With