File: semaphore_test.cpp

package info (click to toggle)
libassa 3.5.1-8.1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,424 kB
  • sloc: cpp: 15,703; sh: 12,083; makefile: 379; perl: 51
file content (98 lines) | stat: -rw-r--r-- 2,219 bytes parent folder | download | duplicates (9)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// -*- c++ -*-
//------------------------------------------------------------------------------
//                         semaphore_test.cpp
//------------------------------------------------------------------------------
// $Id: semaphore_test.cpp,v 1.5 2006/07/20 02:30:56 vlg Exp $
//------------------------------------------------------------------------------
//  Copyright (c) 2002 by Vladislav Grinchenko
//
//  This program is free software; you can redistribute it and/or
//  modify it under the terms of the GNU General Public License
//  as published by the Free Software Foundation; either version
//  2 of the License, or (at your option) any later version.
//------------------------------------------------------------------------------

#include <iostream>
using namespace std;

#include <assert.h>

#if !defined (WIN32)
#   include <sys/ipc.h>		// ftok(2)
#endif

#include "assa/Assure.h"
#include "assa/Fork.h"
#include "assa/Semaphore.h"
#include "assa/CommonUtils.h"

using namespace ASSA;

#if !defined (WIN32)
void fork_with_lock (Semaphore& s)
{
	trace("fork_with_lock");

	DL((TRACE,"[Parent] Forking child...\n"));
	Fork f (Fork::KILL_ON_EXIT, Fork::IGNORE_STATUS);

	if (f.isChild ()) {
		char self[] = "*-*-*-*-* [Child]";
		DL((TRACE,"Raising semaphore ...\n"));

		s.signal ();
		s.dump ();
		DL((TRACE,"Sleeping for 10 secs ...\n"));

		ASSA::Utils::sleep_for_seconds (10);
		DL((TRACE,"Child finished !\n")); 
		exit (0);
	}
}
#endif 

int main (int argc, char* argv[])
{

#if !defined (WIN32)

	string log_name ("semaphore_test.log");
	::unlink (log_name.c_str ());
	Log::open_log_file (log_name.c_str ());

	trace("semaphore_test");

	std::cout << "= Running semaphore_test Test =\n";

	key_t key = ftok ("/etc/hosts", 'S');
	assert (key != (key_t) -1);

	Semaphore s;
	s.create (key, 0);
	s.dump ();

	DL((TRACE,"Semaphore created. Press Enter to continue... \n"));

	int c;
	c = cin.get ();

	fork_with_lock (s);

	s.dump ();
	DL((TRACE,"Waiting on semaphore ...\n"));
	s.wait ();

	DL((TRACE,"Got the semaphore ...\n"));
	s.dump ();

	DL((TRACE,"Removing semaphore ...\n"));
	s.remove ();
	DL((TRACE,"Parent finished !\n"));

#endif 
	std::cout << "Test passed\n";

	return 0;
}