void FirstStart(Synchronized* const synchronized)
        {
            //try to take the first lock exclusively, if we get it we may be allowed to call Create
            //                const bool gotLock = m_fileLock->try_lock();
            m_firstExclusiveLock = boost::interprocess::scoped_lock<boost::interprocess::file_lock>
                (m_firstLock,boost::interprocess::try_to_lock);
            if (m_firstExclusiveLock.owns())
            {
                //Ok, got the first lock. Now see if we can get the second lock
                m_secondExclusiveLock = boost::interprocess::scoped_lock<boost::interprocess::file_lock>
                    (m_secondLock,boost::interprocess::try_to_lock);
                if (m_secondExclusiveLock.owns())
                {
                    //We got it! We're allowed to start initializing everything

                    //remove any semaphore left over from previous instances
                    boost::interprocess::named_semaphore::remove(m_name.c_str());

                    //invoke the user callback
                    synchronized->Create();

                    boost::interprocess::permissions perms;
                    perms.set_unrestricted();

                    //Create a new semaphore so that users know if we succeeded or not.
                    boost::interprocess::named_semaphore sem(boost::interprocess::create_only,m_name.c_str(),1,perms);
                }

                m_firstExclusiveLock.unlock();
            }

            //Wait for the exclusive lock to be released (or, if we're the Creator, just get the shared lock)
            //this will cause everyone to wait for Create to have completed successfully.
            m_firstSharableLock = boost::interprocess::sharable_lock<boost::interprocess::file_lock>
                (m_firstLock);

            try
            {
                //Try to *open* the semaphore. If it has not been created this will cause an exception
                //to be thrown.
                boost::interprocess::named_semaphore sem(boost::interprocess::open_only,m_name.c_str());

                sem.wait();
                sem.post();
            }
            catch (const boost::interprocess::interprocess_exception& exc)
            {
                std::ostringstream ostr;
                ostr << "It appears that Create failed in some other process for '"
                     << m_name << "'." << std::endl;
                ostr << "The exception I got was " << exc.what()
                     << " and strerror(errno) returned this info: "
                     << strerror(errno) << std::endl;
                std::wcerr << ostr.str().c_str() << std::flush;
                throw std::logic_error(ostr.str());
            }

            //invoke user callback
            synchronized->Use();
        }
Ejemplo n.º 2
0
void * test1_main(void *ptr)
{
    Test1.Init();
       
#ifdef _EDROOM_IS_DEBUG_

    Pr_SemaphoreRec sem("Sem");
    
    Pr_Task ptask0(test1_thread0, "task", EDROOMprioLow, 512);
    Pr_Task ptask1(test1_thread1, "task2", EDROOMprioNormal, 512);
    Pr_Task ptask2(test1_thread2, "task3", EDROOMprioHigh, 512);

#else

    Pr_SemaphoreRec sem;
    
    Pr_Task ptask0(test1_thread0, EDROOMprioLow, 512);
    Pr_Task ptask1(test1_thread1, EDROOMprioNormal, 512);
    Pr_Task ptask2(test1_thread2, EDROOMprioHigh, 512);

#endif

    semrec[0] = &sem;
    
    task[0] = &ptask0;
    task[1] = &ptask1;
    task[2] = &ptask2;
    
    printf("\n\nStarting TEST1:\nResource Semaphore Test\n\n");
    
    Test1.Start();
    
    printf("\n\nTEST1: Finised!\n\n");
    return NULL;
}
Ejemplo n.º 3
0
RexxMethod2(int, alarm_startTimer, wholenumber_t, numdays, wholenumber_t, alarmtime)
{
    SysSemaphore sem(true);              /* Event-semaphore                   */
    int  msecInADay = 86400000;          /* number of milliseconds in a day   */

    /* set the state variables           */
    context->SetObjectVariable("EVENTSEMHANDLE", context->NewPointer(&sem));
    context->SetObjectVariable("TIMERSTARTED", context->True());

    while (numdays > 0)
    {                /* is it some future day?            */
        // use the semaphore to wait for an entire day.
        // if this returns true, then this was not a timeout, which
        // probably means this was cancelled.
        if (sem.wait(msecInADay))
        {
            /* Check if the alarm is canceled. */
            RexxObjectPtr cancelObj = context->GetObjectVariable("CANCELED");

            if (cancelObj == context->True())
            {
                return 0;
            }
            else
            {
                sem.reset();              /* Reset the event semaphore         */
            }
        }
        numdays--;                         /* Decrement number of days          */
    }

    // now we can just wait for the alarm time to expire
    sem.wait(alarmtime);
    return 0;
}
Ejemplo n.º 4
0
inline void windows_semaphore::post(long release_count)
{
   sync_handles &handles =
      windows_intermodule_singleton<sync_handles>::get();
   winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0));
   sem.post(release_count);
}
Ejemplo n.º 5
0
//---------------------------------------------------------
// Launch the secondary thread in which the Python interpreter
// is executed, since this call comes from the main Application thread.
//
void Tart::start() {
    if (m_thread)
        return;

    QSemaphore sem(0);

    // qDebug() << QThread::currentThreadId() << "Tart: starting TartThread";
    m_thread = new TartThread(&sem);

    this->moveToThread(m_thread);
    m_thread->start();

    connect(m_thread, SIGNAL(finished()),
        this, SLOT(thread_finished()));

    // being able to acquire this semaphore means the Python main thread
    // has succesfully started, and
    qDebug() << QThread::currentThreadId() << "Tart: wait for sema";
    sem.acquire(1);
    qDebug() << QThread::currentThreadId() << "Tart: got sema";

    // Only make the connection here if the interpreter entered the event loop.
    if (m_thread->ran_loop()) {
        // force postMessage() to result in a QueuedConnection for now
        // since the default doesn't appear to be picking the right method
        // TODO: investigate if that's a sign of a problem
        connect(this,
            SIGNAL(postMessage(QString)),
            this,
            SLOT(do_postMessage(QString)),
            Qt::QueuedConnection);
    }
}
Ejemplo n.º 6
0
bool PollThread::checkDigikamInstancesRunning()
{
    QSystemSemaphore sem("DigikamDBSrvAccess", 1, QSystemSemaphore::Open);
    sem.acquire();
    QDBusConnectionInterface* interface = QDBusConnection::sessionBus().interface();
    QDBusReply<QStringList> reply       = interface->registeredServiceNames();

    if (reply.isValid())
    {
        QStringList serviceNames = reply.value();
        QLatin1String digikamStartupService("org.kde.digikam.startup-");
        QLatin1String digikamService("org.kde.digikam-");
        QLatin1String digikamKioService("org.kde.digikam.KIO-");
        foreach (const QString& service, serviceNames)
        {
            if (service.startsWith(digikamStartupService) ||
                service.startsWith(digikamService) ||
                service.startsWith(digikamKioService))
            {
                kDebug() << "At least service ["<< service <<"] is using the database server";

                // At least one digikam/kio service was found
                sem.release(1);
                return true;
            }
        }
    }
Ejemplo n.º 7
0
inline bool windows_semaphore::try_wait(void)
{
   sync_handles &handles =
      windows_intermodule_singleton<sync_handles>::get();
   //This can throw
   winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0));
   return sem.try_wait();
}
Ejemplo n.º 8
0
inline bool windows_semaphore::timed_wait(const lslboost::posix_time::ptime &abs_time)
{
   sync_handles &handles =
      windows_intermodule_singleton<sync_handles>::get();
   //This can throw
   winapi_semaphore_functions sem(handles.obtain_semaphore(this->id_, 0));
   return sem.timed_wait(abs_time);
}
Ejemplo n.º 9
0
TEST(Semaphore, ConstructorTest2)
{
	const int TestCount = 123;
	asd::Semaphore sem(TestCount);
	ASSERT_EQ(sem.GetCount(), TestCount);
	for (int i=0; i<TestCount; ++i) {
		ASSERT_TRUE(sem.Wait(0));
	}
	ASSERT_EQ(sem.GetCount(), 0);
}
Ejemplo n.º 10
0
int release()
{
    QSystemSemaphore sem("store");
    if (!sem.release()) {
        qWarning() << "Could not release" << sem.key();
        return EXIT_FAILURE;
    }
    qDebug("done releasing");
    return EXIT_SUCCESS;
}
Ejemplo n.º 11
0
void * test2_main(void *ptr)
{

    SynchrERROR = 1;
    
    Test2.Init();
    
#ifdef _EDROOM_IS_DEBUG_

    Pr_SemaphoreBin sem("Sem", 0);
    Pr_SemaphoreBin sem2("Sem2", 0);
    
    Pr_Task ptask1(test2_thread1, "task1", EDROOMprioHigh,512);
    Pr_Task ptask2(test2_thread2, "task2", EDROOMprioNormal,512);
    Pr_Task ptask3(test2_thread0, "taskStart", EDROOMprioVeryHigh,512);
    
#else

    Pr_SemaphoreBin sem(0);
    Pr_SemaphoreBin sem2(0);
    
    Pr_Task ptask1(test2_thread1, EDROOMprioHigh,512);
    Pr_Task ptask2(test2_thread2, EDROOMprioNormal,512);
    Pr_Task ptask3(test2_thread0, EDROOMprioVeryHigh,512);
    
#endif    

    sembin[0] = &sem;
    sembin[1] = &sem2;
    
    task[1] = &ptask1;
    task[2] = &ptask2;
    task[0] = &ptask3;

    printf("\n\nStarting TEST2:\nTest for Pr_Send and Pr_Receive\n\n");
    
    Test2.Start();
   
    printf("\n\nTEST2: Finished!\n\n"); 
    return NULL;
}
Ejemplo n.º 12
0
int acquirerelease()
{
    QSystemSemaphore sem("store");
    if (!sem.acquire()) {
        qWarning() << "Could not acquire" << sem.key();
        return EXIT_FAILURE;
    }
    if (!sem.release()) {
        qWarning() << "Could not release" << sem.key();
        return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
}
Ejemplo n.º 13
0
int acquire(int count = 1)
{
    QSystemSemaphore sem("store");

    for (int i = 0; i < count; ++i) {
        if (!sem.acquire()) {
            qWarning() << "Could not acquire" << sem.key();
            return EXIT_FAILURE;
        }
    }
    qDebug("done aquiring");
    return EXIT_SUCCESS;
}
Ejemplo n.º 14
0
void DatabaseServerStarter::stopServerManagerProcess()
{
    QSystemSemaphore sem(QLatin1String("DigikamDBSrvAccess"), 1, QSystemSemaphore::Open);
    sem.acquire();

    if (isServerRegistered())
    {
        QDBusInterface dbus_iface(QLatin1String("org.kde.digikam.DatabaseServer"), QLatin1String("/DatabaseServer"));
        QDBusMessage stateMsg = dbus_iface.call(QLatin1String("isRunning"));

        if (stateMsg.arguments().at(0).toBool())
        {
            dbus_iface.call(QLatin1String("stopDatabaseProcess"));
        }
    }

    sem.release();
}
Ejemplo n.º 15
0
void PspSpeedTests::semaphoreSpeed() {
	PspSemaphore sem(1);

	uint32 time1 = PspRtc::instance().getMicros();

	sem.take();

	uint32 time2 = PspRtc::instance().getMicros();

	PSP_INFO_PRINT("taking semaphore took %d us\n", time2-time1);	// 10us

	uint32 time3 = PspRtc::instance().getMicros();

	sem.give();

	uint32 time4 = PspRtc::instance().getMicros();
	PSP_INFO_PRINT("releasing semaphore took %d us\n", time4-time3);	//10us-55us
}
Ejemplo n.º 16
0
 const Signals::SemaphorePtr&
 Signals::SignalTable::AddSemaphore(const ConnectionId & connection)
 {
     const size_t semSize = m_semaphores.size();
     if (semSize >= 300)
     {
         lllout << "PERFORMING SIGNAL GARBAGE COLLECTION!" << std::endl;
         for (int i = 0; i < 50; ++i)
         {
             Semaphores::iterator it = m_semaphores.begin();
             std::advance(it,rand() % (semSize - i));
             m_semaphores.erase(it);
         }
     }
     const std::string name = GetSemaphoreName(connection);
     SemaphorePtr sem(new NamedSemaphore(name));
     return m_semaphores.insert(std::make_pair(connection.m_id, sem)).
         first->second;
 }
Ejemplo n.º 17
0
void MiscThreadTestCase::TestSemaphore()
{
    static const int SEM_LIMIT = 3;

    wxSemaphore sem(SEM_LIMIT, SEM_LIMIT);
    ArrayThreads threads;

    for ( int i = 0; i < 3*SEM_LIMIT; i++ )
    {
        threads.Add(new MySemaphoreThread(i, &sem));
        CPPUNIT_ASSERT_EQUAL( wxTHREAD_NO_ERROR, threads.Last()->Run() );
    }

    for ( size_t n = 0; n < threads.GetCount(); n++ )
    {
        CPPUNIT_ASSERT_EQUAL( 0, (long)threads[n]->Wait() );
        delete threads[n];
    }
}
Ejemplo n.º 18
0
/**
    把基本义原从文件读入vector
*/
void ReadCorpus::ReadSememe(const std::string str_filename)
{
    std::ifstream ifs(str_filename.c_str());
    if(!ifs.is_open())
    {
        std::cout<<"Read file: "<<str_filename<<" error!"<<std::endl;
        exit(ERROR_OPENFILE);
    }
    std::string str_line;
    while(getline(ifs,str_line))
    {
        std::istringstream iss(str_line);
        int index,pind;
        std::string str_sememe;
        iss>>index>>str_sememe>>pind;
        Sememe sem(index,str_sememe,pind);
        vec_Sememe.push_back(sem);
    }
    ifs.close();
}
Ejemplo n.º 19
0
int main()
{
	Semaphore sem(5, 100);
	ThreadTest t1;
	
	t1.m_Sem = &sem;
	
	t1.Start();
	
	for (int i = 0; i < 50; i++)
	{
#ifdef WIN32
		Sleep(1000);
#elif defined( LINUX )
		sleep(1);
#endif
		sem.Up();
		std::cout << "Up" << std::endl;
	}
	
	t1.WaitForShutdown();
	return 0;
}
Ejemplo n.º 20
0
void
FilterDilation::apply()
{
#if defined(HAVE_IPP)
	IppStatus status;

	if (se == NULL) {
		// standard 3x3 dilation

		IppiSize size;
		size.width  = src_roi[0]->width - 2;
		size.height = src_roi[0]->height - 2;

		if ((dst == NULL) || (dst == src[0])) {
			// In-place

			// std::cout << "Running in-place with standard SE" << std::endl;

			status = ippiDilate3x3_8u_C1IR(src[0] + ((src_roi[0]->start.y + 1) * src_roi[0]->line_step)
			                                 + ((src_roi[0]->start.x + 1) * src_roi[0]->pixel_step),
			                               src_roi[0]->line_step,
			                               size);

		} else {
			// std::cout << "Running not in-place dilation with standard SE" << std::endl;

			status = ippiDilate3x3_8u_C1R(src[0] + ((src_roi[0]->start.y + 1) * src_roi[0]->line_step)
			                                + ((src_roi[0]->start.x + 1) * src_roi[0]->pixel_step),
			                              src_roi[0]->line_step,
			                              dst + ((dst_roi->start.y + 1) * dst_roi->line_step)
			                                + ((dst_roi->start.x + 1) * dst_roi->pixel_step),
			                              dst_roi->line_step,
			                              size);

			yuv422planar_copy_uv(src[0],
			                     dst,
			                     src_roi[0]->image_width,
			                     src_roi[0]->image_height,
			                     src_roi[0]->start.x,
			                     src_roi[0]->start.y,
			                     src_roi[0]->width,
			                     src_roi[0]->height);
		}
	} else {
		// we have a custom SE

		IppiSize size;
		size.width  = src_roi[0]->width - se_width;
		size.height = src_roi[0]->height - se_width;

		IppiSize  mask_size   = {se_width, se_height};
		IppiPoint mask_anchor = {se_anchor_x, se_anchor_y};

		/*
    std::cout << "Dilation filter is running with the following parameters:" << std::endl
	      << "  ROI size:    " << size.width << " x " << size.height << std::endl
	      << "  mask size:   " << mask_size.width << " x " << mask_size.height << std::endl
	      << "  mask anchor: (" << mask_anchor.x  << "," << mask_anchor.y << ")" << std::endl
	      << std::endl;

    printf("  src buf:     0x%x\n", (unsigned int)src );
    printf("  dst buf:     0x%x\n", (unsigned int)dst );
    */

		if ((dst == NULL) || (dst == src[0])) {
			// In-place

			status =
			  ippiDilate_8u_C1IR(src[0]
			                       + ((src_roi[0]->start.y + (se_height / 2)) * src_roi[0]->line_step)
			                       + ((src_roi[0]->start.x + (se_width / 2)) * src_roi[0]->pixel_step),
			                     src_roi[0]->line_step,
			                     size,
			                     se,
			                     mask_size,
			                     mask_anchor);

		} else {
			//std::cout << "Running NOT in-place" << std::endl;

			status =
			  ippiDilate_8u_C1R(src[0] + ((src_roi[0]->start.y + (se_height / 2)) * src_roi[0]->line_step)
			                      + ((src_roi[0]->start.x + (se_width / 2)) * src_roi[0]->pixel_step),
			                    src_roi[0]->line_step,
			                    dst + ((dst_roi->start.y + (se_height / 2)) * dst_roi->line_step)
			                      + ((dst_roi->start.x + (se_width / 2)) * dst_roi->pixel_step),
			                    dst_roi->line_step,
			                    size,
			                    se,
			                    mask_size,
			                    mask_anchor);

			yuv422planar_copy_uv(src[0],
			                     dst,
			                     src_roi[0]->image_width,
			                     src_roi[0]->image_height,
			                     src_roi[0]->start.x,
			                     src_roi[0]->start.y,
			                     src_roi[0]->width,
			                     src_roi[0]->height);
		}
	}

	if (status != ippStsNoErr) {
		throw fawkes::Exception("Morphological dilation failed with %i\n", status);
	}
#elif defined(HAVE_OPENCV)
	cv::Mat srcm(src_roi[0]->height,
	             src_roi[0]->width,
	             CV_8UC1,
	             src[0] + (src_roi[0]->start.y * src_roi[0]->line_step)
	               + (src_roi[0]->start.x * src_roi[0]->pixel_step),
	             src_roi[0]->line_step);

	if (dst == NULL) {
		dst     = src[0];
		dst_roi = src_roi[0];
	}

	cv::Mat dstm(dst_roi->height,
	             dst_roi->width,
	             CV_8UC1,
	             dst + (dst_roi->start.y * dst_roi->line_step)
	               + (dst_roi->start.x * dst_roi->pixel_step),
	             dst_roi->line_step);

	if (se == NULL) {
		cv::dilate(srcm, dstm, cv::Mat());
	} else {
		cv::Mat   sem(se_width, se_height, CV_8UC1);
		cv::Point sem_anchor(se_anchor_x, se_anchor_y);
		cv::dilate(srcm, dstm, sem, sem_anchor);
	}
#endif
}
Ejemplo n.º 21
0
int main(int argc, char *argv[])
{
	int   ch, i, conn_timeout = 2, rw_timeout = 2, redis_connections = 10;
	acl::string addr("127.0.0.1:6379");

	while ((ch = getopt(argc, argv, "hs:n:c:p:r:t:")) > 0) {
		switch (ch) {
		case 'h':
			usage(argv[0]);
			return 0;
		case 's':
			addr = optarg;
			break;
		case 'n':
			__oper_count = atoi(optarg);
			break;
		case 'c':
			__fibers_count = atoi(optarg);
			__fibers_max = __fibers_count;
			break;
		case 'p':
			redis_connections = atoi(optarg);
			break;
		case 'r':
			rw_timeout = atoi(optarg);
			break;
		case 't':
			conn_timeout = atoi(optarg);
			break;
		default:
			break;
		}
	}

	acl::acl_cpp_init();

	// declare redis cluster
	acl::redis_client_cluster cluster;
	cluster.set(addr, 0, conn_timeout, rw_timeout);

	// declare fiber sem
	acl::fiber_sem sem(redis_connections);

	std::vector<fiber_redis*> fibers;

	gettimeofday(&__begin, NULL);

	for (i = 0; i < __fibers_count; i++)
	{
		fiber_redis* fiber = new fiber_redis(cluster, sem);
		fibers.push_back(fiber);
		fiber->start(320000);
	}

	acl_fiber_schedule();

	for (std::vector<fiber_redis*>::iterator it = fibers.begin();
		it != fibers.end(); ++it)
	{
		delete *it;
	}

	return 0;
}
Ejemplo n.º 22
0
int main(int argc,char *argv[])
{
	int	_pid = 0;
	int 	ret=0;
	key_t 	key;
	int intping = 60;	// ping银行间隔
	int intflush = 60;	// 冲正间隔
	int inttrans = 60;	//划拨间隔
	int intcomp = 10;	//对帐时间间隔
	struct 	shmid_ds buf;

	BANK_TRANS_REQUEST	bank_trans;

   	int opt;
   	extern int optind;
   	extern char *optarg;

	while ((opt = getopt(argc, argv, "bdvhi:p:f:")) != EOF)
	{
		switch(opt)
		{
		case 'v':
			printf("bank guard version 1.0.2.10\n");
			return 0;
		case 'b':
			app_flag |= APP_FLAG_DAEMON;
			break;
		case 'd':
			app_flag |= APP_FLAG_DEBUG;
			debug = 2;
			break;
		case 'i':
			app_flag |= APP_FLAG_CONFIG;
			ReadIni(optarg);
			break;
		case 'p':
			intping = atol(optarg);
			break;
		case 'f':
			intflush = atol(optarg);
			break;
		case '?':
		case 'h':
		default:
			printf("usage: %s -options \n", argv[0]);
			printf("\toptions:\n");
			printf("\t-b\t\trun as daemon\n");
			printf("\t-d\t\trun in debug mode, communication content will be printed to stdout\n");
			printf("\t-h\t\tshow this help message\n");
			printf("\t-i inifile\tassign config file\n");
			printf("\t-p ping_interval\tassign the interval between each ping\n");
			printf("\t-f flush_interval\tassign the interval between each database process\n");
			return 0;
		}
	}

 	// 屏蔽信号
	signal(SIGPIPE, sig_handler);
	signal(SIGALRM, sig_handler);
	signal(SIGINT, sig_handler);
	signal(SIGHUP, sig_handler);
	signal(SIGTERM, sig_handler);
	signal(SIGCHLD, sig_handler);

 	if((app_flag&APP_FLAG_CONFIG) == 0)
		ReadIni("trans.ini");

	if((app_flag&APP_FLAG_DAEMON)!= 0)
 	{
 		_pid=fork();
		if(_pid != 0)
			exit(0);
		else if(_pid< 0)
			exit(1);

		setsid();
		_pid=fork();
		if(_pid != 0)
			exit(0);
		else if(_pid< 0)
			exit(1);

		int i;
		for(i=3;i<20;++i)
			close(i);

		//umask(0);
 	}

    	openlog("bank",LOG_PID|LOG_CONS|LOG_NDELAY,LOG_LOCAL4);

	// 初始化数据库连接:
	SQLInitialize();
	ret = SQLConnectToServer();
	if (ret!=0)
	{
		writelog(LOG_ERR,"连接数据库失败[%d]", ret);
		//printf("连接数据库失败database %s, username %s, password %s, [%d]", g_BUnit.m_SqlDB.szDatabase,g_BUnit.m_SqlDB.szLogin,g_BUnit.m_SqlDB.szPassword, ret);
		printf("连接数据库失败\n");
		return 	E_DB_DBCONN;
	}

   	//创建共享内存
	key=ftok(".",0);
	shmid=shmget(key,SEGSIZE,IPC_CREAT|0666);
	if(-1==shmid)
	{
		writelog(LOG_ERR,"创建共享内存失败[%d]",shmid);
		printf("创建共享内存失败\n");
		return 	E_CREATE_SHARE_MEMORY;
	}
	shm=(char*)shmat(shmid,0,0);
	if((int)shm==-1)
	{
		writelog(LOG_ERR,"连接共享内存失败[%d]",shm);
		printf("连接共享内存失败\n");
		return 	E_JOIN_SHARE_MEMORY;
	}


	//枷锁进行清除设备签到表和前置机签到
	semid=sem(key);
	if((int)semid==-1)
	{
		writelog(LOG_ERR,"创建信号量失败[%d]",semid);
		printf("创建信号量失败\n");
		return 	E_JOIN_SHARE_MEMORY;
	}

	p(semid);

	//初始化共享内存
	memset(shm, 0, SEGSIZE);
	shm[0]=0;
	shm[1]=0;
	writelog(LOG_INFO,"已重置共享内存");
	ret=DB_t_pif_device_update_by_subsystem_type(SUBSYSTYPE_KEEP,SUBSYSSTAT_OFFLINE);
	//if(ret)
	if((ret!=0)&&(ret!=100))
	{
		writelog(LOG_ERR,"DB_t_pif_device_update_by_subsystem_type error,errcode=[%d]",ret);
		shmdt(shm);
		shmctl(shmid,IPC_RMID,&buf);
		d_sem(semid);
		return 	ret;
	}

	shm[2]=1;
	writelog(LOG_ERR,"已清理设备表");

	//枷锁退出
	v(semid);

	//writelog(LOG_INFO,"银行接口初始化完成,bank_bu可以启动了");
	//printf("银行接口初始化完成\n");

	time_t	now = 0;
	time_t 	lastping = 0;		// 上次ping银行时间
	time_t	lastflush = 0;		// 上次处理冲正时间
	time_t	lasttrans=0;		//上次试图帐务划拨的时间
	time_t	lastcomp=0;		//上次试图银行对帐的时间
	T_t_tif_tradeserial  tradeserial; //卡操作流水表,用做冲正用

	// 进入运行
	while(true)
	{
		if((app_flag&APP_FLAG_TERM) != 0)
		{
			writelog(LOG_INFO,"收到终止信号,退出");
			break;
		}

		// 监测与银行通信情况

		now = time(0);
		if((now - lastping) > intping)
		{

			lastping = now;
			if(shm[1] != 1)
			{
				//进行系统登陆,修改登陆标志
				p(semid);

				writelog(LOG_INFO,"开始登陆银行");
				printf("正在登陆银行...\n");

				shm[0]=1;

				ret=Do_Login(&bank_trans);
				if(ret!=0)
				{
					writelog(LOG_ERR,"登陆银行失败[%d]",ret);
					printf("----------登陆银行失败----------\n");
				}
				else
				{
					writelog(LOG_INFO,"登陆银行成功");
					printf("----------登陆银行成功----------\n");
					shm[1]=1;
					shm[3]=0;
					memcpy(shm+10,bank_trans.BankCardPwd,sizeof(bank_trans.BankCardPwd));

					ret=call_240006();
					if((ret!=0)&&(ret!=100))
					{
						writelog(LOG_ERR,"Call 240006 error,errcode=[%d]",ret);
						shmdt(shm);
						shmctl(shmid,IPC_RMID,&buf);
						d_sem(semid);
						return 	ret;
					}

					shm[2]=1;
					writelog(LOG_INFO,"已清理设备表");

					char buffer[100]="";
					int k=0;
					for(int i=0;i<16;i++)
					{
						k=bank_trans.BankCardPwd[i];
						sprintf(&buffer[2*i],"%02X",k);
					}
					writelog(LOG_INFO,"BankCardPwd=[%s]",buffer);
				}
				v(semid);
				continue;
			}

			ret=Do_CheckLine(&bank_trans);
			if(ret != 0)	// ret?
			{
				writelog(LOG_ERR,"与银行的通信可能中断[%d]",ret);
				p(semid);
				shm[1]=0;	// 置登陆标志,// 是否有必要重新登陆??
				shm[3]=1;	// 置通信标志
				v(semid);
			}
			else if(shm[3] == 1)
			{
				writelog(LOG_ERR,"与银行的通信恢复[%d]",ret);
				p(semid);
				shm[3]=0;	// 置通信标志
				v(semid);
			}

		}

		//补发冲正
		now = time(0);
		if((now - lastflush) > intflush)
		{
			lastflush = now;
			//获取下一个冲正记录:状态为需冲正且上次冲正时间最早
			//RESERVE_1不为空的视为冲正成功
			ret = call_240004(&tradeserial);
			if( ret == 0)
			{
				ret = Do_DeTrans(&tradeserial,&bank_trans); 
				if(ret == 0)
				{
					// 更新该冲正记录状态(发送时间、次数)
					// 保留银行端流水号BankSn
					if(0!=strncmp(bank_trans.RetCode,RET_BANK_OK,2))
					{
						writelog(LOG_ERR,"冲正失败,retcode=[%2.2s]",bank_trans.RetCode);
						ret=call_240005();
					}
					else
					{
						writelog(LOG_INFO,"补发冲正记录成功[%ld]", tradeserial.serial_no);
						memcpy(tradeserial.reserve_1, bank_trans.BankSn, sizeof(bank_trans.BankSn));
						ret=call_240005();
					}
				}
				else
				{
					writelog(LOG_INFO,"补发冲正记录失败[%ld]", tradeserial.serial_no);
					ret=call_240005();
				}
			}
		}

		//做银行对帐
		char buffer[20]="";
		int ho_OpCount=0;
		double ho_Fee_Change=0;
		int ret=0;
		now = time(0);
		if((now - lastcomp) > intcomp)
		{
			lastcomp=now;
			//判断系统时间是否到达早6点
			if(0==memcmp("06",getsystime(NULL),2))
			{
				ret=call_240007();
				if(ret)
				{
					writelog(LOG_ERR,"Do_Compare_file error[%d]", ret);
				}
				writelog(LOG_ERR,"Do_Compare_file complete");
			}
		}
		// 休眠
		sleep(5);//13938470950

	}

	p(semid);
	shm[3]=0;	// 置通信标志
	v(semid);

	shmdt(shm);
	shmctl(shmid,IPC_RMID,&buf);
	d_sem(semid);

	SQLExit();
	writelog(LOG_INFO, "程序正常退出");
	printf("程序正常退出\n");
	return(0);
}
Ejemplo n.º 23
0
void Database::SaverLoader::load()
{
    tUV.clear();
    tEtudiant.clear();
    tFormation.clear();
    tCategorie.clear();
    tNote.clear();
    tSaison.clear();
    tSemestre.clear();
    //load Notes
    string q="SELECT note, description, rang, eliminatoire FROM Note;";
    QSqlQuery res=db.query(q);
    while(res.next())
    {
        Note note(res.value(0).toString(),res.value(1).toString(),res.value(2).toUInt(),res.value(3).toUInt());
    }

    //load Saisons
     q="SELECT nom, description FROM Saison;";
     res=db.query(q);
    while(res.next())
    {
        Saison Sais(res.value(0).toString(),res.value(1).toString());
    }

    //load Semestres
     q="SELECT code, saison, year FROM Semestre;";
     res=db.query(q);
    while(res.next())
    {
        Semestre sem(tSaison.getElement(res.value(1).toString()),res.value(2).toInt());
    }
    qDebug()<<"test";

    //load Catégories

    q="SELECT code, description FROM Categorie;";
    res=db.query(q);
    while(res.next())
    {
        Categorie cat(res.value(0).toString(),res.value(1).toString());
    }
    qDebug()<<"test";
    //Mise en place des sous Catégories
    for(std::vector<Categorie>::iterator it_cat=tCategorie.getIterator();it_cat!=tCategorie.end();it_cat++)
    {
        q="SELECT codeParent, codeFille FROM SousCategorie where codeParent='"+it_cat->getCode().toStdString()+"';";
        res=db.query(q);
        while(res.next())
        {
            tCategorie.getElement(res.value(0).toString()).addSousCategorie(tCategorie.getElement(res.value(1).toString()));
        }
    }
    qDebug()<<"test";

    //load UVS
    q="SELECT code, titre, automne, printemps FROM UV;";
    res=db.query(q);
    while(res.next())
    {
       map<Categorie, unsigned int> uvcre=map<Categorie, unsigned int>();
       string q1="SELECT code, categorie, nbCredits FROM CreditsUV WHERE code='"+res.value(0).toString().toStdString()+"';";
       QSqlQuery res1=db.query(q1);
       while(res1.next())
       {
           uvcre[StringToCategorie(res1.value(1).toString())]=res1.value(2).toInt();
       }
       UV(res.value(0).toString().toStdString(), res.value(1).toString().toStdString(), uvcre, res.value(2).toBool(), res.value(3).toBool());

    }
    //load Formation
    q="SELECT nom, description FROM Formation;";
    res=db.query(q);
    while(res.next())
    {
        map<UV*, bool> uvs=map<UV*, bool>();
        string q1="SELECT formation, uv, obligatoire FROM FormationUV where formation='"+res.value(0).toString().toStdString()+"';";
        QSqlQuery res1=db.query(q1);
        while(res1.next())
        {
            UV& uv=tUV.getElement(res1.value(1).toString().toStdString());
            uvs[&uv]=res1.value(2).toBool();
        }
        map<Categorie, unsigned int> Cat=map<Categorie, unsigned int>();
        q1="SELECT formation, categorie, nbCredits FROM CreditsFormation where formation='"+res.value(0).toString().toStdString()+"';";
        res1=db.query(q1);
        while(res1.next())
        {
            Cat[StringToCategorie(res1.value(1).toString())]=res1.value(2).toInt();
        }

        std::vector<Condition> conds;
        q1="SELECT formation, condition FROM conditionsFormation where formation='"+res.value(0).toString().toStdString()+"';";
        res1=db.query(q1);
        while(res1.next())
        {
           conds.push_back(Condition(res1.value(1).toString()));
        }
        Formation(res.value(0).toString(), res.value(1).toString(), uvs, Cat,conds);
    }

    //load Etudiants
    q="SELECT ine, login, nom, prenom, dateNaissance from Etudiant;";
    res=db.query(q);
    while(res.next())
    {
        vector<Inscription> insc= vector<Inscription>();
        string q1="SELECT login, code, saison, annee, resultat FROM Inscription WHERE login='******';";
        QSqlQuery res1=db.query(q1);
        while(res1.next())
        {
            //Semestre s=Semestre(StringToSaison(res1.value(2).toString()), res1.value(3).toInt());
            string code=res1.value(1).toString().toStdString();
            const UV& uv=tUV.getElement(code);
            Inscription inscription=Inscription(uv, tSemestre.getElement(res1.value(2).toString()+res1.value(3).toString()), StringToNote(res1.value(4).toString()));
            insc.push_back(inscription);
        }
        vector<Formation*> form= vector<Formation*>();
        q1="SELECT login, formation FROM FormationEtudiant WHERE login='******';";
        res1=db.query(q1);
        while(res1.next())
        {
            Formation& F=tFormation.getElement(res1.value(1).toString().toStdString());
            form.push_back(&F);
        }
        Dossier dos=Dossier(insc, form);
        Etudiant etu=Etudiant(dos, res.value(0).toInt(), res.value(2).toString(), res.value(3).toString(), res.value(4).toDate(), res.value(1).toString());
        qDebug()<<"fin load";
    }
}
Ejemplo n.º 24
0
int main(int argc,char *argv[])
{
	FILE *fp = NULL;
	int	_pid = 0;
	int 	ret=0;
	key_t 	key;
	char sign[2]="I";
	int debug=0;
	int intping = 60;	// ping银行间隔
	int intflush = 10;	// 冲正间隔
	int inttrans = 60;	//划拨间隔
	int intcomp = 10;	//对帐时间间隔
	char strTemp[256]="";
	struct 	shmid_ds buf;
	int terminal_id=0;
	int send_flag = 0;			// 发送请求标识, 有的银行不需要发送请求标识, 有的需要(信合需要, 农行不需要)
	int send_count = 0;			// 发送对账请求的次数, 超过一次请求就不允许了再发请求了, 除非发送失败
	
	//BANK_TRANS_REQUEST	bank_trans;
	INNER_TRANS_REQUEST  inner_trans;
	BANK_COMPARE_FILE compare_file, compare_src_file;				// 对账文件描述
	BANK_COMPARE_RECODE compare_record;			// 对账文件记录描述
	BANK_FILE_ADJUST file_adjust;				// 对账文件所需效验的数据字段
	memset(&compare_file, 0, sizeof(compare_file));
	memset(&compare_src_file, 0, sizeof(compare_src_file));
	memset(&compare_record, 0, sizeof(compare_record));
	memset(&file_adjust, 0, sizeof(file_adjust));
	
   	int opt;
   	extern int optind;
   	extern char *optarg;

	ST_PACK ArrayPack;			// 设置返回包
	ST_CPACK aPack;				// 设置应答包
	ST_PACK *out_pack = &(aPack.pack);
	ST_CPACK sPack;			 	// 设置发送包

	ResetNormalCPack(&aPack, 0, 1);
	memset(&ArrayPack, 0, sizeof(ArrayPack));



	memset(&inner_trans,0,sizeof inner_trans);
	
	while ((opt = getopt(argc, argv, "bdvhi:p:f:")) != EOF)
	{
		switch(opt)
		{
		case 'v':
			printf("bank guard version 1.0.2.10\n");
			return 0;
		case 'b':
			app_flag |= APP_FLAG_DAEMON;
			break;
		case 'd':
			app_flag |= APP_FLAG_DEBUG;
			debug = 2;
			break;
		case 'i':
			app_flag |= APP_FLAG_CONFIG;
			ReadIni_bank(&g_Bank);
			break;
		case 'p':
			intping = atol(optarg);
			break;
		case 'f':
			intflush = atol(optarg);
			break;
		case '?':
		case 'h':
		default:
			printf("usage: %s -options \n", argv[0]);
			printf("\toptions:\n");
			printf("\t-b\t\trun as daemon\n");
			printf("\t-d\t\trun in debug mode, communication content will be printed to stdout\n");
			printf("\t-h\t\tshow this help message\n");
			printf("\t-i inifile\tassign config file\n");
			printf("\t-p ping_interval\tassign the interval between each ping\n");
			printf("\t-f flush_interval\tassign the interval between each database process\n");
			return 0;
		}
	}

 	// 屏蔽信号
	signal(SIGPIPE, sig_handler);
	signal(SIGALRM, sig_handler);
	signal(SIGINT, sig_handler);
	signal(SIGHUP, sig_handler);
	signal(SIGTERM, sig_handler);
	signal(SIGCHLD, sig_handler);

 	if((app_flag&APP_FLAG_CONFIG) == 0)
		ReadIni_bank(&g_Bank);

	if((app_flag&APP_FLAG_DAEMON)!= 0)
 	{
 		_pid=fork();
		if(_pid != 0)
			exit(0);
		else if(_pid< 0)
			exit(1);

		setsid();
		_pid=fork();
		if(_pid != 0)
			exit(0);
		else if(_pid< 0)
			exit(1);

		int i;
		for(i=3;i<20;++i)
			close(i);

		//umask(0);
 	}

    	openlog("bank",LOG_PID|LOG_CONS|LOG_NDELAY,LOG_LOCAL4);

	//创建共享内存
	key=ftok("bankguard",9);

	//key=ftok(".",0);
	shmid=shmget(key,SEGSIZE,IPC_CREAT|0666);
	if(-1==shmid)
	{
		writelog(LOG_ERR,"创建共享内存失败[%d]",shmid);
		printf("创建共享内存失败\n");
		return 	E_CREATE_SHARE_MEMORY;
	}
	shm=(char*)shmat(shmid,0,0);
	if((int)shm==-1)
	{
		writelog(LOG_ERR,"连接共享内存失败[%d]",shm);
		printf("连接共享内存失败\n");
		return 	E_JOIN_SHARE_MEMORY;
	}

	//枷锁进行清除设备签到表和前置机签到
	semid=sem(key);
	if((int)semid==-1)
	{
		writelog(LOG_ERR,"创建信号量失败[%d]",semid);
		printf("创建信号量失败\n");
		return 	E_JOIN_SHARE_MEMORY;
	}

	p(semid);

	//初始化共享内存
	memset(shm, 0, SEGSIZE);
	shm[0]=0;
	shm[1]=0;
	writelog(LOG_INFO,"已重置共享内存");

	if(!KS_YKT_Clt::Initialize(g_Bank.DRTP_IP, g_Bank.DRTP_PORT, g_Bank.BCC_BASEFUNCNO))
	{
		printf("----------初始化通讯平台失败----------\n");
		shmdt(shm);
		shmctl(shmid,IPC_RMID,&buf);
		d_sem(semid);
		return 	-1;
	}
	KS_YKT_Clt ykt_clt;
	char msg[256]="";
	ykt_clt.ResetHandler();

	//shm[2]=1;

	//枷锁退出
	v(semid);

	time_t	now = 0;
	time_t 	lastping = 0;		// 上次ping银行时间
	time_t	lastflush = 0;		// 上次处理冲正时间
	time_t	lasttrans=0;		//上次试图帐务划拨的时间
	time_t	lastcomp=0;		//上次试图银行对帐的时间

	// 进入运行
	while(true)
	{
		if((app_flag&APP_FLAG_TERM) != 0)
		{
			writelog(LOG_INFO,"收到终止信号,退出");
			break;
		}
		// 监测与银行通信情况
		now = time(0);
		if((now - lastping) > intping)
		{
			lastping = now;
			if(shm[1] != 1)
			{
				p(semid);	//进行系统登陆,修改登陆标志
				writelog(LOG_INFO,"开始登陆银行");
				printf("正在登陆银行...\n");
				shm[0]=1;
				ret=SignInOut(&inner_trans,&g_Bank,sign);
				if(ret!=0)
				{
					writelog(LOG_ERR,"登陆银行失败[%d]",ret);
					printf("----------登陆银行失败----------\n");
				}
				else
				{
					writelog(LOG_INFO,"登陆银行成功");
					printf("----------登陆银行成功----------\n");
					shm[1]=1;
					shm[3]=0;
					memcpy(shm+10,inner_trans.BankCardPwd,sizeof(inner_trans.BankCardPwd));
					shm[2]=1;

					char buffer[100]="";
					int k=0;
					for(int i=0;i<16;i++)
					{
						k=inner_trans.BankCardPwd[i];
						sprintf(&buffer[2*i],"%02X",k);
					}
					writelog(LOG_INFO,"BankCardPwd=[%s]",buffer);
				}
				v(semid);
				continue;
			}

			ret=Bank_CheckLine();
			if(ret != 0)	// ret?
			{
				writelog(LOG_ERR,"与银行的通信可能中断[%d]",ret);
				p(semid);
				shm[1]=0;	// 置登陆标志,// 是否有必要重新登陆??
				shm[3]=1;	// 置通信标志
				v(semid);
			}
			else if(shm[3] == 1)
			{
				writelog(LOG_ERR,"与银行的通信恢复[%d]",ret);
				p(semid);
				shm[3]=0;	// 置通信标志
				v(semid);
			}

		}

		//补发冲正
		now = time(0);
		//if((now - lastflush) > intflush)
		if(0>1)
		{
			writelog(LOG_ERR,"Start flush!");
			lastflush = now;
			//获取下一个冲正记录:状态为需冲正且上次冲正时间最早
			//RESERVE_1不为空的视为冲正成功
			ykt_clt.ResetHandler();
			if(!ykt_clt.SendRequest(240004, g_Bank.TIMEOUT*1000))
			{
				ykt_clt.GetReturnMsg(msg);
				writelog(LOG_ERR,"retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
			}
			else if(ykt_clt.GetReturnCode())
			{
				ykt_clt.GetReturnMsg(msg);
				writelog(LOG_ERR,"retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
			}
			else
			{
				if(ykt_clt.HasMoreRecord())
				{
					ykt_clt.GetNextPackage();
					GET_PACK_STR(ykt_clt,"sdate0",strTemp);
					memcpy(inner_trans.TradeDate,strTemp,sizeof inner_trans.TradeDate);
					GET_PACK_STR(ykt_clt,"stime0",strTemp);
					memcpy(inner_trans.TradeTime,strTemp,sizeof inner_trans.TradeTime);
					GET_PACK_STR(ykt_clt,"sorder0",strTemp);
					memcpy(inner_trans.TransMoney,strTemp,sizeof inner_trans.TransMoney);
					GET_PACK_STR(ykt_clt,"sserial0",strTemp);
					memcpy(inner_trans.CardNo,strTemp,sizeof inner_trans.CardNo);
					GET_PACK_STR(ykt_clt,"scust_auth",strTemp);
					memcpy(inner_trans.BankCardNo,strTemp,sizeof inner_trans.BankCardNo);

					ykt_clt.GetIntFieldByName("lvol0",&inner_trans.RecvNo);
					ykt_clt.GetIntFieldByName("lvol1",&inner_trans.SendNo);
					ykt_clt.GetIntFieldByName("lvol2",&terminal_id);
					sprintf(inner_trans.TerminalId,"%d",terminal_id);
					writelog(LOG_ERR,"当前流水号=[%d], 冲正流水号=[%d], 日期=[%s], 时间=[%s], 交易卡号=[%d], 银行卡号=[%s], 终端号=[%d]", inner_trans.SendNo, inner_trans.RecvNo, inner_trans.TradeDate, inner_trans.TradeTime, atoi(inner_trans.CardNo), inner_trans.BankCardNo, terminal_id);
					ret = Bank_Undo(&inner_trans); 
					if(ret == 0)
					{
						writelog(LOG_ERR,"发送银行冲正记录成功[%ld]", inner_trans.SendNo);
						ykt_clt.ResetHandler();
						ykt_clt.SetIntFieldByName("lvol0", inner_trans.SendNo);
						ykt_clt.SetIntFieldByName("lvol1", 1);

						if(!ykt_clt.SendRequest(240005, g_Bank.TIMEOUT*1000))
						{
							ykt_clt.GetReturnMsg(msg);
							writelog(LOG_ERR,"调用后台确认冲正功能失败retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
						}
						if(ykt_clt.GetReturnCode())
						{
							ykt_clt.GetReturnMsg(msg);
							writelog(LOG_ERR,"调用后台确认冲正功能失败retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
						}

					}
					else
					{
						writelog(LOG_ERR,"发送银行冲正记录失败[%ld]", inner_trans.SendNo);
						ykt_clt.ResetHandler();
						ykt_clt.SetIntFieldByName("lvol0", inner_trans.SendNo);
						ykt_clt.SetIntFieldByName("lvol1", 0);

						if(!ykt_clt.SendRequest(240005, g_Bank.TIMEOUT*1000))
						{
							ykt_clt.GetReturnMsg(msg);
							writelog(LOG_ERR,"调用后台确认冲正功能失败retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
						}
						if(ykt_clt.GetReturnCode())
						{
							ykt_clt.GetReturnMsg(msg);
							writelog(LOG_ERR,"调用后台确认冲正功能失败retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
						}
					}

				}
				else
				{
					writelog(LOG_ERR,"Return package error,retcode=[%d],msg=[%s]",ykt_clt.GetReturnCode(),msg);
				}
			}
		}
		L_RETU:
		// 休眠
		sleep(5);//13938470950	
	}
	if ( shm[1]==1)
	ret=SignInOut(&inner_trans,&g_Bank,sign);
	p(semid);
	shm[3]=0;	// 置通信标志
	v(semid);

	shmdt(shm);
	shmctl(shmid,IPC_RMID,&buf);
	d_sem(semid);
	
	writelog(LOG_INFO, "程序正常退出");
	printf("程序正常退出\n");
	return(0);
}
Ejemplo n.º 25
0
DatabaseServerError DatabaseServerStarter::startServerManagerProcess(const QString& dbType)
{
    DatabaseServerError result;

    /*
     * TODO:
     * 1. Acquire semaphore lock on "DigikamDBSrvAccess"
     * 2. Check if there is an database server manager service already registered on DBus
     * 3. If not, start the database server manager
     * 4. Release semaphore lock
     */
    QSystemSemaphore sem(QLatin1String("DigikamDBSrvAccess"), 1, QSystemSemaphore::Open);
    sem.acquire();

    if (!isServerRegistered())
    {
        const QString dbServerMgrPath = QString::fromUtf8(LIBEXEC_INSTALL_DIR) + QLatin1String("/digikamdatabaseserver");

        if ( dbServerMgrPath.isEmpty() )
        {
            qCDebug(DIGIKAM_DBENGINE_LOG) << "No path to digikamdatabaseserver set in server manager configuration!";
        }

        const QStringList arguments;

        bool result = QProcess::startDetached( dbServerMgrPath, arguments );

        if ( !result )
        {
            qCDebug(DIGIKAM_DBENGINE_LOG) << "Could not start database server manager !";
            qCDebug(DIGIKAM_DBENGINE_LOG) << "executable:" << dbServerMgrPath;
            qCDebug(DIGIKAM_DBENGINE_LOG) << "arguments:" << arguments;
        }
    }

    // wait until the server has successfully registered on DBUS
    // TODO Use another way for that! Sleep isn't good :-/

    for (int i = 0; i < 30; ++i)
    {
        if (!isServerRegistered())
        {
            QThread sleepThread;
            sleepThread.msleep(250);
            sleepThread.wait();
        }
        else
        {
            break;
        }
    }

    QDBusInterface dbus_iface(QLatin1String("org.kde.digikam.DatabaseServer"), QLatin1String("/DatabaseServer"));
    QDBusMessage stateMsg = dbus_iface.call(QLatin1String("isRunning"));

    if (!stateMsg.arguments().at(0).toBool())
    {
        DatabaseServerError error;

        QList<QVariant> arguments;
        arguments.append(dbType);

        QDBusMessage reply = dbus_iface.callWithArgumentList(QDBus::Block, QLatin1String("startDatabaseProcess"), arguments);

        if (QDBusMessage::ErrorMessage == reply.type())
        {
            result.setErrorType(DatabaseServerError::StartError);
            result.setErrorText(i18n("<p><b>Error while calling the database server starter.</b></p>"
                                     "Details:\n %1", reply.errorMessage()));
        }
        else
        {
            arguments                = reply.arguments();
            QDBusVariant dbusVariant = qvariant_cast<QDBusVariant>(arguments.at(1));
            // Retrieve the actual value stored in the D-Bus variant
            QVariant dbusArgument    = dbusVariant.variant();
            DatabaseServerError item = qdbus_cast<DatabaseServerError>(dbusArgument);
            result                   = item;
        }
    }

    sem.release();

    return result;
}
Ejemplo n.º 26
0
u32 semaphore_create(s32 initial_val, s32 max_val, u32 protocol, u64 name_u64)
{
	std::shared_ptr<semaphore_t> sem(new semaphore_t(protocol, max_val, name_u64, initial_val));

	return Emu.GetIdManager().GetNewID(sem, TYPE_SEMAPHORE);
}
Ejemplo n.º 27
0
TEST(TestFoundation, blocking_queue)
{
  //
  // Test if semaphores can be set prior to a wait
  //
  OSS::semaphore sem(0,100);
  sem.set();
  ASSERT_TRUE(sem.tryWait(0));
  ASSERT_FALSE(sem.tryWait(0));

  //
  // Test semaphore/queue combo
  //
  OSS::BlockingQueue<int> q;
  for (int i = 0; i < 100; i++)
    q.enqueue(i);

  for (int i = 0; i < 100; i++)
  {
    int x;
    q.dequeue(x);
    ASSERT_EQ(i, x);
  }

  int x = 999;
  ASSERT_FALSE(q.try_dequeue(x, 100));
  ASSERT_EQ(x, 999);

  //
  // Verify md5 encryption
  //
  std::stringstream in;
  in << "this is a sample md5 input";
  std::ostringstream out;
  OSS::crypto_md5_encode(in, out);
  std::string md5 = OSS::string_md5_hash(in.str().c_str());
  ASSERT_STREQ(out.str().c_str(), md5.c_str());

  //
  // Verify md5 encryption using sip
  //
  std::stringstream a1;
  std::ostringstream ha1;

  a1 << "17772322706:callcentric.com:durak1";
  OSS::crypto_md5_encode(a1, ha1);

  std::stringstream a2;
  std::ostringstream ha2;

  a2 << "INVITE:sip:[email protected];transport=udp";
  OSS::crypto_md5_encode(a2, ha2);
  std::string nonce = "0ae63a71bda5f5ac40ea3b73151b2062";
  
  std::stringstream hmd5;
  std::ostringstream hmd5response;

  hmd5 << ha1.str() << ":" << nonce << ":" << ha2.str();
  OSS::crypto_md5_encode(hmd5, hmd5response);
  ASSERT_STREQ(hmd5response.str().c_str(), "b1eef0d24f098ac498f1bf342c9eff12");

  std::vector<char> b64Out;
  OSS::crypto_base64_decode("Y29kZT0xMjM0LXVzZXJuYW1lPTMzMDQ1LW1hYz0wMDEyMDAxMjAwOQ==", b64Out);
  ASSERT_STREQ(&b64Out[0], "code=1234-username=33045-mac=00120012009");

  std::string replaceStr = "FreeSWITCH KarooBridge FreeSWITCH";
  OSS::string_replace(replaceStr, "FreeSWITCH", "KarooBridge");
  ASSERT_STREQ(replaceStr.c_str(), "KarooBridge KarooBridge KarooBridge");


}
Ejemplo n.º 28
0
int
main( int argc, char * argv[] )
{

  if( (App = new AppParam( argc, argv, VERID_main ) ) == 0 )
    {
      cerr << "Can't new AppParam." << endl;
      exit( 1 );
    }

  if( ! App->good() || App->help() || ! App->allArgs() )
    App->abort( 1, true, __FILE__, __LINE__ );


  FileStat  lockstat( App->lockFn() );
    
  if( ! lockstat.good() )
    {
      AppError << lockstat.error() << endl;
      return( 1 );
    }

  Semaphore sem( App->lockFn() );

  if( ! sem.good() )
    {
      AppError << sem.error() << endl;
      return( 1 );
    }

  FileLock  lock( App->lockFn(), (ios::openmode)(ios::in | ios::out) );

  if( ! lock.good() )
    {
      AppError << lock.error() << endl;
      return( 1 );
    }

  if( ! sem.islocked() )
    {
      if( ! lock.lockread() )
	{
	  AppError << lock.error() << endl;
	  return( 1 );
	}
    }
  
  for( ;; )
    {
      AppDebug << "Sleeping for '" << App->sleepTime() << "' seconds." << endl;
      
      sleep( App->sleepTime() );
      
      if( sem.islocked() )
	{
	  AppDebug << "sem LOCKED." << endl;

	  if( ! lock.unlock() )
	    {
	      AppError << lock.error() << endl;
	      return( 1 );
	    }
	  else
	    {
	      AppDebug << "read UNLOCKED." << endl;
	    }
	  
	  if( ! sem.waitfor() )
	    {
	      AppError << sem.error() << endl;
	    }

	  if( ! lock.lockread() )
	    {
	      AppError << lock.error() << endl;
	      return( 1 );
	    }
	  else
	    {
	      AppDebug << "read LOCKED." << endl;
	    }
	  
	  if( sem.islocked() )
	    {
	      AppError << "still LOCKED!!!" << endl;
	      return( 1 );
	    }
	  
	  AppDebug << "sem UNLOCKED." << endl;
	}
    }
  
  return( 0 );
}
Ejemplo n.º 29
0
bool QSEngineImp::evaluate( const QString &code, const QSObject *thisV,
                            bool onlyCheckSyntax, int checkMode, int lineZero )
{
#if defined (QT_THREAD_SUPPORT) && QT_VERSION >= 0x030300
    QMutex *mutex = qt_global_mutexpool ? qt_global_mutexpool->get(qApp) : 0;
#endif
    QS_MUTEX_LOCK;
    QSProgramNode *progNode = 0;

    init();

#ifdef QSDEBUGGER
    incrSourceId();
    if (debugger())
        debugger()->setSourceId(sid);
#endif
    if (recursion > 7) {
        qWarning( "QtScript: breaking out of recursion" );
        QS_MUTEX_UNLOCK;
        return true;
    }

    assert(QSLexer::lexer());
    {
        QSLexer::lexer()->setCode( code,
#ifdef QSDEBUGGER
                                   sourceId(),
#else
                                   0,
#endif
                                   lineZero );
        int parseError = qsyyparse();
        progNode = QSProgramNode::last();

        if( parseError || QSLexer::lexer()->lexerState() == QSLexer::Bad ) {
            errType = QSErrParseError;
            int l = QSLexer::lexer()->lineNo();
            errLines.append( l );
            errMsgs.append( QString::fromLatin1("Parse Error: ")
                            + qs_format_error( QSLexer::lexer()->errorMessage() ) );
            /* TODO: either clear everything or keep previously
               parsed function definitions */
            //    QSNode::deleteAllNodes();
            if (progNode && progNode->deref()) {
                delete progNode;

            }
            QS_MUTEX_UNLOCK;
            return false;
        }
    }

    QSCheckData sem( env(), env()->globalClass() );
    if ( thisV ) {
        Q_ASSERT( thisV->isValid() );
        //       qDebug( "QSEngineImp::evaluate: entering %s",
        // 	      thisV->typeName().latin1());
        sem.enterClass( (QSClass*)thisV->objectType() );
        env()->pushScope( *thisV );
    }
    sem.setGlobalStatementsForbidden( checkMode & QSEngine::DisallowGlobal );
    progNode->check( &sem );
    if ( sem.hasError() ) {
        errType = sem.errorCode();
        errLines = sem.errorLines();
        errMsgs = sem.errorMessages();
        if (progNode->deref())
            delete progNode;
        QS_MUTEX_UNLOCK;
        return FALSE;
    }

    if (onlyCheckSyntax) {
        if (progNode->deref()) {
            delete progNode;
        }
        QS_MUTEX_UNLOCK;
        return true;
    }

    env()->clearException();

    recursion++;
    assert(progNode);

    QS_MUTEX_UNLOCK;
    QSObject res = progNode->execute( env() );
    QS_MUTEX_LOCK;

    recursion--;

    if ( env()->isExceptionMode( )) {
        QSObject err = env()->exception();
        errType = 99; /* TODO */
        errLines.append(QSErrorClass::errorLine(&err));
        errMsgs.append(QSErrorClass::errorName(&err) + QString::fromLatin1(". ") + QSErrorClass::errorMessage(&err));
#ifdef QSDEBUGGER
        if (dbg)
            dbg->setSourceId(QSErrorClass::errorSourceId(&err));
#endif
        env()->clearException();
    } else {
        errType = 0;
        errLines.clear();
        errMsgs.clear();

        // catch return value
        retVal = res;
    }

    if ( thisV ) {
        env()->popScope();
    }

    if (progNode->deref()) {
        delete progNode;
    }

    QS_MUTEX_UNLOCK;
    return !errType;
}
Ejemplo n.º 30
0
int main(int argc,char *argv[])
{
	FILE *fp = NULL;
	int	_pid = 0;
	int 	ret=0;
	key_t 	key;
	int intping = 60;	// ping银行间隔
	int intflush = 10;	// 冲正间隔
	int inttrans = 60;	//划拨间隔
	int intcomp = 10;	//对帐时间间隔
	char strTemp[256]="";
	struct 	shmid_ds buf;
	int terminal_id=0;
	int send_flag = 0;			// 发送请求标识, 有的银行不需要发送请求标识, 有的需要(信合需要, 农行不需要)
	int send_count = 0;			// 发送对账请求的次数, 超过一次请求就不允许了再发请求了, 除非发送失败
	
	//BANK_TRANS_REQUEST	bank_trans;
	INNER_TRANS_REQUEST  inner_trans;
	BANK_COMPARE_FILE compare_file, compare_src_file;				// 对账文件描述
	BANK_COMPARE_RECODE compare_record;			// 对账文件记录描述
	BANK_FILE_ADJUST file_adjust;				// 对账文件所需效验的数据字段
	memset(&compare_file, 0, sizeof(compare_file));
	memset(&compare_src_file, 0, sizeof(compare_src_file));
	memset(&compare_record, 0, sizeof(compare_record));
	memset(&file_adjust, 0, sizeof(file_adjust));
	
   	int opt;
   	extern int optind;
   	extern char *optarg;

	ST_PACK ArrayPack;			// 设置返回包
	ST_CPACK aPack;				// 设置应答包
	ST_PACK *out_pack = &(aPack.pack);
	ST_CPACK sPack;			 	// 设置发送包

	ResetNormalCPack(&aPack, 0, 1);
	memset(&ArrayPack, 0, sizeof(ArrayPack));



	memset(&inner_trans,0,sizeof inner_trans);
	
	while ((opt = getopt(argc, argv, "bdvhi:p:f:")) != EOF)
	{
		switch(opt)
		{
		case 'v':
			printf("bank guard version 1.0.2.10\n");
			return 0;
		case 'b':
			app_flag |= APP_FLAG_DAEMON;
			break;
		case 'd':
			app_flag |= APP_FLAG_DEBUG;
			debug = 2;
			break;
		case 'i':
			app_flag |= APP_FLAG_CONFIG;
			ReadIni_bank(&g_Bank);
			break;
		case 'p':
			intping = atol(optarg);
			break;
		case 'f':
			intflush = atol(optarg);
			break;
		case '?':
		case 'h':
		default:
			printf("usage: %s -options \n", argv[0]);
			printf("\toptions:\n");
			printf("\t-b\t\trun as daemon\n");
			printf("\t-d\t\trun in debug mode, communication content will be printed to stdout\n");
			printf("\t-h\t\tshow this help message\n");
			printf("\t-i inifile\tassign config file\n");
			printf("\t-p ping_interval\tassign the interval between each ping\n");
			printf("\t-f flush_interval\tassign the interval between each database process\n");
			return 0;
		}
	}

 	// 屏蔽信号
	signal(SIGPIPE, sig_handler);
	signal(SIGALRM, sig_handler);
	signal(SIGINT, sig_handler);
	signal(SIGHUP, sig_handler);
	signal(SIGTERM, sig_handler);
	signal(SIGCHLD, sig_handler);

 	if((app_flag&APP_FLAG_CONFIG) == 0)
		ReadIni_bank(&g_Bank);

	if((app_flag&APP_FLAG_DAEMON)!= 0)
 	{
 		_pid=fork();
		if(_pid != 0)
			exit(0);
		else if(_pid< 0)
			exit(1);

		setsid();
		_pid=fork();
		if(_pid != 0)
			exit(0);
		else if(_pid< 0)
			exit(1);

		int i;
		for(i=3;i<20;++i)
			close(i);

		//umask(0);
 	}

    	openlog("bank",LOG_PID|LOG_CONS|LOG_NDELAY,LOG_LOCAL4);

	//创建共享内存
	key=ftok("bankguard",9);

	//key=ftok(".",0);
	shmid=shmget(key,SEGSIZE,IPC_CREAT|0666);
	if(-1==shmid)
	{
		writelog(LOG_ERR,"创建共享内存失败[%d]",shmid);
		printf("创建共享内存失败\n");
		return 	E_CREATE_SHARE_MEMORY;
	}
	shm=(char*)shmat(shmid,0,0);
	if((int)shm==-1)
	{
		writelog(LOG_ERR,"连接共享内存失败[%d]",shm);
		printf("连接共享内存失败\n");
		return 	E_JOIN_SHARE_MEMORY;
	}

	//枷锁进行清除设备签到表和前置机签到
	semid=sem(key);
	if((int)semid==-1)
	{
		writelog(LOG_ERR,"创建信号量失败[%d]",semid);
		printf("创建信号量失败\n");
		return 	E_JOIN_SHARE_MEMORY;
	}

	p(semid);

	//初始化共享内存
	memset(shm, 0, SEGSIZE);
	shm[0]=0;
	shm[1]=0;
	writelog(LOG_INFO,"已重置共享内存");

	if(!KS_YKT_Clt::Initialize(g_Bank.DRTP_IP, g_Bank.DRTP_PORT, g_Bank.BCC_BASEFUNCNO))
	{
		printf("----------初始化通讯平台失败----------\n");
		shmdt(shm);
		shmctl(shmid,IPC_RMID,&buf);
		d_sem(semid);
		return 	-1;
	}
	KS_YKT_Clt ykt_clt;
	char msg[256]="";
	ykt_clt.ResetHandler();

	//shm[2]=1;

	//枷锁退出
	v(semid);

	time_t	now = 0;
	time_t 	lastping = 0;		// 上次ping银行时间
	time_t	lastflush = 0;		// 上次处理冲正时间
	time_t	lasttrans=0;		//上次试图帐务划拨的时间
	time_t	lastcomp=0;		//上次试图银行对帐的时间

	// 进入运行
	while(true)
	{
		if((app_flag&APP_FLAG_TERM) != 0)
		{
			writelog(LOG_INFO,"收到终止信号,退出");
			break;
		}
		// 监测与银行通信情况
		now = time(0);
		if((now - lastping) > intping)
		{
			lastping = now;
			//判断系统时间是否到达早5点半
			/*
			if(0==memcmp("0530",getsystime(NULL),4))
			{
				shm[1]= 0;				// 重置共享内存,要求重新登录
			}
			
			if(shm[1] != 1)
			{
				p(semid);	//进行系统登陆,修改登陆标志
				writelog(LOG_INFO,"开始登陆银行");
				printf("正在登陆银行...\n");
				shm[0]=1;
				ret=Bank_SignIn(&inner_trans);
				if(ret!=0)
				{
					writelog(LOG_ERR,"登陆银行失败[%d]",ret);
					printf("----------登陆银行失败----------\n");
				}
				else
				{
					writelog(LOG_INFO,"登陆银行成功");
					printf("----------登陆银行成功----------\n");
					shm[1]=1;
					shm[3]=0;
					memcpy(shm+10,inner_trans.BankCardPwd,sizeof(inner_trans.BankCardPwd));
					shm[2]=1;

					char buffer[100]="";
					int k=0;
					for(int i=0;i<16;i++)
					{
						k=inner_trans.BankCardPwd[i];
						sprintf(&buffer[2*i],"%02X",k);
					}
					writelog(LOG_INFO,"BankCardPwd=[%s]",buffer);
				}
				v(semid);
				continue;
			}
			*/
		}
		sleep(30);
	}


	p(semid);
	shm[3]=0;	// 置通信标志
	v(semid);

	shmdt(shm);
	shmctl(shmid,IPC_RMID,&buf);
	d_sem(semid);
	
	writelog(LOG_INFO, "程序正常退出");
	printf("程序正常退出\n");
	return(0);
}