1 // Copyright (c) 1999-2018 David Muse
2 // See the file COPYING for more information
3 
4 #include <rudiments/sharedmemory.h>
5 #include <rudiments/charstring.h>
6 #include <rudiments/stringbuffer.h>
7 #include <rudiments/permissions.h>
8 #include <rudiments/file.h>
9 #include <rudiments/directory.h>
10 #include <rudiments/snooze.h>
11 #include <rudiments/process.h>
12 #include <rudiments/stdio.h>
13 #include "test.cpp"
14 
main(int argc,const char ** argv)15 int main(int argc, const char **argv) {
16 
17         sharedmemory    shm;
18 
19 	const char	*str="This string is in shared memory.";
20 
21 	if (argc==1) {
22 
23 		header("sharedmemory");
24 
25 		if (!sharedmemory::supported()) {
26 			stdoutput.printf("	not supported\n\n");
27 			return 0;
28 		}
29 
30 		stdoutput.write("setup...\n");
31 
32 		// create the key file
33 		file::remove("shmkey");
34 		file	fd;
35 		test("key file",fd.create("shmkey",
36 				permissions::evalPermString("rw-------")));
37 		fd.close();
38 
39 		// create a 128 byte shared memory segment
40         	sharedmemory    shm;
41         	test("create shm",
42 			shm.create(file::generateKey("shmkey",1),128,
43                                 permissions::evalPermString("rw-------")));
44 
45 		// write a string into the shared memory
46         	test("write",charstring::copy(
47         			(char *)shm.getPointer(),
48 				"This string is in shared memory.")==
49         			(char *)shm.getPointer());
50 
51 		// spawn the second process (to write 2, 4)
52 		stringbuffer	cmd;
53 		char	*pwd=directory::getCurrentWorkingDirectory();
54 		cmd.append(pwd)->append("/sharedmemory");
55 		#ifdef _WIN32
56 			cmd.append(".exe");
57 		#endif
58 		delete[] pwd;
59 		const char	*args1[]={"sharedmemory","child",NULL};
60 		process::spawn(cmd.getString(),args1,true);
61 
62 		snooze::macrosnooze(1);
63 
64 		// clean up key file
65 		file::remove("shmkey");
66 
67 	} else {
68 
69 		// attach to the shared memory segment
70         	test("attach to shm",
71 			shm.attach(file::generateKey("shmkey",1),128));
72 
73 		// display the data contained in the shared memory segment
74         	test("read",!charstring::compare((char *)shm.getPointer(),str));
75         	stdoutput.printf("\n");
76 	}
77 }
78