コード例 #1
0
ファイル: test1.c プロジェクト: yunxiaoxiao110/haiku
int32 test_thread(void *data)
{
    int tnum = *(int*)data;
    int sock = 0;
    uint32 num = 0;
    bigtime_t tn;

    printf("Thread %d, starting test...\n", tnum + 1);

    tn = real_time_clock();

    while (real_time_clock() - tn <= TIME) {
        sock = socket(AF_INET, SOCK_DGRAM , 0);
        if (sock < 0) {
            printf("Failed! Socket could not be created.\n");
            printf("Error was %d [%s]\n", sock, strerror(sock));
            printf("This was after I had created %ld socket%s\n",
                   num, num == 1 ? "" : "s");
            return -1;
        }
        closesocket(sock);
        num++;
    }

    printf( "Thread %d:\n"
            "       sockets created : %5ld\n"
            "       test time       : %5d seconds\n"
            "       average         : %5ld sockets/sec\n",
            tnum + 1, num, TIME, num / TIME);
}
コード例 #2
0
ファイル: select_test.c プロジェクト: SummerSnail2014/haiku
int main(int argc, char **argv)
{
	int s;
	int rv;
	struct fd_set fdr, fdw, fde;
	struct timeval tv;
	int32 rtc;
	
	test_banner("Select test");
			
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0)
		err(s, "Socket creation failed");

	FD_ZERO(&fdr);
	FD_SET(s, &fdr);
	FD_ZERO(&fdw);
	FD_SET(s, &fdw);
	FD_ZERO(&fde);
	FD_SET(s, &fde);
	
	tv.tv_sec = 5;
	tv.tv_usec = 0;
	
	printf("Trying with timeval (5 secs)...\n");
	rtc = real_time_clock();
	rv = select(s + 1, &fdr, NULL, &fde, &tv);
	rtc = real_time_clock() - rtc;
	printf("select gave %d in %ld seconds\n", rv, rtc);
	if (rv < 0)
		printf("errno = %d [%s]\n", errno, strerror(errno));

	printf("resetting select fd's\n");
	FD_ZERO(&fdr);
	FD_SET(s, &fdr);
	FD_ZERO(&fdw);
	FD_SET(s, &fdw);
	FD_ZERO(&fde);
	FD_SET(s, &fde);
	
	printf("Trying without timeval (= NULL)\n");
	rv = select(s +1, &fdr, &fdw, &fde, NULL);
	printf("select gave %d\n", rv);
	
	if (FD_ISSET(s, &fdr))
		printf("Data to read\n");
	if (FD_ISSET(s, &fdw))
		printf("OK to write\n");
	if (FD_ISSET(s, &fde))
		printf("Exception!\n");
		
	closesocket(s);
	
	printf("Test complete.\n");

	return (0);
}
コード例 #3
0
ファイル: AutoFiler.cpp プロジェクト: HaikuArchives/Filer
static void
LaunchFiler(const entry_ref& ref)
{
	static uint32 launchTime = real_time_clock();

	RefStorage* refholder;
	team_id team;
	entry_ref dirRef;
	BEntry dir, file(&ref);
	BMessage msg(B_REFS_RECEIVED);

	file.GetParent(&dir);
	dir.GetRef(&dirRef);
	msg.AddRef("refs", &ref);

	gRefLock.Lock();

	for (int32 i = 0; i < gRefStructList.CountItems(); i++)
	{
		refholder = (RefStorage*) gRefStructList.ItemAt(i);

		if (refholder->ref == dirRef)
		{
			if (refholder->doAll && real_time_clock() > launchTime)
				refholder->doAll = false;

			msg.AddBool(kDoAll, refholder->doAll);
			msg.AddBool(kReplace, refholder->replace);
			break;
		}
	}

	be_roster->Launch(kFilerSignature, &msg, &team);

	if (!refholder->doAll)
	{
		BMessage reply;
		be_app_messenger.SetTo(NULL, team);

		if (be_app_messenger.SendMessage(MSG_AUTO_FILER, &reply) == B_OK)
		{
			reply.FindBool(kDoAll, &refholder->doAll);
			reply.FindBool(kReplace, &refholder->replace);
		}
	}

	launchTime = real_time_clock();

	gRefLock.Unlock();
}
コード例 #4
0
ファイル: ClipView.cpp プロジェクト: humdingerb/clipdinger
void
ClipView::AdjustColors()
{
	bool fade;
	int32 delay;
	int32 step;
	float maxlevel;
	bool pause;
	ClipdingerSettings* settings = my_app->Settings();
	if (settings->Lock()) {
		fade = settings->GetFade();
		step = settings->GetFadeStep();
		delay = settings->GetFadeDelay() * kMinuteUnits;
		maxlevel = 1.0 + 0.025 * settings->GetFadeMaxLevel();
		pause = settings->GetFadePause();
		settings->Unlock();
	}

	if (pause)
		return;

	bigtime_t now(real_time_clock());
	for (int32 i = 0; i < CountItems(); i++) {
		ClipItem* sItem = dynamic_cast<ClipItem *> (ItemAt(i));
		if (fade) {
			bigtime_t minutes = (now - sItem->GetTimeSince()) / 60;
			float level = B_NO_TINT
				+ (maxlevel / step * ((float)minutes / delay) / kMinuteUnits);
			sItem->SetColor(tint_color(ui_color(B_LIST_BACKGROUND_COLOR),
			(level < maxlevel) ? level : maxlevel));  // limit to maxlevel
		} else
			sItem->SetColor(ui_color(B_LIST_BACKGROUND_COLOR));
	}
}
コード例 #5
0
BString
BStatusView::_TimeStatusString(float availableSpace, float* _width)
{
	double totalBytesPerSecond = (double)(fSizeProcessed
			- fEstimatedFinishReferenceSize)
		* 1000000LL / (system_time() - fEstimatedFinishReferenceTime);
	double secondsRemaining = (fTotalSize - fSizeProcessed)
		/ totalBytesPerSecond;
	time_t now = (time_t)real_time_clock();
	time_t finishTime = (time_t)(now + secondsRemaining);

	char timeText[32];
	const BLocale* locale = BLocale::Default();
	if (finishTime - now > kSecondsPerDay) {
		locale->FormatDateTime(timeText, sizeof(timeText), finishTime,
			B_MEDIUM_DATE_FORMAT, B_MEDIUM_TIME_FORMAT);
	} else {
		locale->FormatTime(timeText, sizeof(timeText), finishTime,
			B_MEDIUM_TIME_FORMAT);
	}

	BString string(_FullTimeRemainingString(now, finishTime, timeText));
	float width = StringWidth(string.String());
	if (width > availableSpace) {
		string.SetTo(_ShortTimeRemainingString(timeText));
		width = StringWidth(string.String());
	}

	if (_width != NULL)
		*_width = width;
	return string;
}
コード例 #6
0
ファイル: ProjectWindow.cpp プロジェクト: passick/Paladin
int32
ProjectWindow::BackupThread(void *data)
{
	ProjectWindow *parent = (ProjectWindow*)data;
	Project *proj = parent->fProject;
	
	char timestamp[32];
	time_t t = real_time_clock();
	strftime(timestamp,32,"_%Y-%m-%d-%H%M%S",localtime(&t));
	
	BPath folder(proj->GetPath().GetFolder());
	BPath folderparent;
	folder.GetParent(&folderparent);
	
	BString command = "cd '";
	command << folderparent.Path() << "'; ";
	command << "zip -9 -r -y '"
			<< gBackupPath.GetFullPath() << "/"
			<< proj->GetName() << timestamp << "' '"
			<< folder.Leaf() << "' -x *.o";
	
	system(command.String());
	
	parent->Lock();
	parent->fStatusBar->SetText("");
	parent->SetMenuLock(false);
	parent->Unlock();
	
	return 0;
}
コード例 #7
0
BMailAccountSettings::BMailAccountSettings()
	:
	fStatus(B_OK),
	fInboundEnabled(true),
	fOutboundEnabled(true),
	fModified(true)
{
	fAccountID = real_time_clock();
}
コード例 #8
0
ファイル: WatchView.cpp プロジェクト: DonCN/haiku
int32 WatchView::GetInternetTime()
{
	// First we get the current time as the number of seconds since
	// 1 January 1970 GMT and add an hour's worth of seconds to adjust
	// for the Biel Mean Time (BMT). Then we get the number of seconds
	// that have passed today, and divide it with the length of a beat
	// to get the number of elapsed beats.

	return (int32) (((real_time_clock() + 3600) % 86400) / 86.4);
}
コード例 #9
0
ファイル: time.c プロジェクト: SummerSnail2014/haiku
time_t
time(time_t* timer)
{
	time_t secs = real_time_clock();

	if (timer)
		*timer = secs;

	return secs;
}
コード例 #10
0
ファイル: real_time_clock.cpp プロジェクト: mariuz/haiku
status_t
get_rtc_info(rtc_info *info)
{
	if (info == NULL)
		return B_BAD_VALUE;

	info->time = real_time_clock();
	info->is_gmt = sIsGMT;
	info->tz_minuteswest = sTimezoneOffset / 1000000LL;
	info->tz_dsttime = sDaylightSavingTime;

	return B_OK;
}
コード例 #11
0
void
XsiSemaphoreSet::SetID()
{
	fID = real_time_clock();
	// The lock is held before calling us
	while (true) {
		if (sSemaphoreHashTable.Lookup(fID) == NULL)
			break;
		fID = (fID + 1) % INT_MAX;
	}
	sGlobalSequenceNumber = (sGlobalSequenceNumber + 1) % UINT_MAX;
	fSequenceNumber = sGlobalSequenceNumber;
}
コード例 #12
0
	XsiSemaphoreSet(int numberOfSemaphores, int flags)
		: fInitOK(false),
		fLastSemctlTime((time_t)real_time_clock()),
		fLastSemopTime(0),
		fNumberOfSemaphores(numberOfSemaphores),
		fSemaphores(0)
	{
		mutex_init(&fLock, "XsiSemaphoreSet private mutex");
		SetIpcKey((key_t)-1);
		SetPermissions(flags);
		fSemaphores = new(std::nothrow) XsiSemaphore[numberOfSemaphores];
		if (fSemaphores == NULL) {
			TRACE_ERROR(("XsiSemaphoreSet::XsiSemaphore(): failed to allocate "
				"XsiSemaphore object\n"));
		} else
			fInitOK = true;
	}
コード例 #13
0
bool
SourceFileRez::CheckNeedsBuild(BuildInfo &info, bool check_deps)
{
	if (!info.objectFolder.GetFullPath())
		return false;
	
	if (BString(GetPath().GetExtension()).ICompare("r") != 0)
		return false;
	
	if (BuildFlag() == BUILD_YES)
		return true;
	
	BString objname(GetPath().GetBaseName());
	objname << ".rsrc";
	
	DPath objpath(info.objectFolder);
	objpath.Append(objname);
	if (!BEntry(objpath.GetFullPath()).Exists())
		return true;
	
	BString tmpname(GetPath().GetBaseName());
	tmpname << ".r.txt";
	
	DPath tmppath(info.objectFolder);
	tmppath.Append(tmpname);
	if (!BEntry(tmppath.GetFullPath()).Exists())
		return true;
	
	
	struct stat objstat;
	if (stat(objpath.GetFullPath(),&objstat) != 0)
		return false;
	
	// Fix mod times set into the future
	time_t now = real_time_clock();
	if (GetModTime() > now)
	{
		BNode node(GetPath().GetFullPath());
		node.SetModificationTime(now);
	}
	
	if (GetModTime() > objstat.st_mtime)
		return true;
	
	return false;
}
コード例 #14
0
ファイル: fifo.cpp プロジェクト: mylegacy/haiku
Inode::Inode()
	:
	fReadRequests(),
	fWriteRequests(),
	fReaderCount(0),
	fWriterCount(0),
	fActive(false),
	fReadSelectSyncPool(NULL),
	fWriteSelectSyncPool(NULL)
{
	fWriteCondition.Publish(this, "pipe");
	mutex_init(&fRequestLock, "pipe request");

	bigtime_t time = real_time_clock();
	fModificationTime.tv_sec = time / 1000000;
	fModificationTime.tv_nsec = (time % 1000000) * 1000;
	fCreationTime = fModificationTime;
}
コード例 #15
0
ファイル: kernel_interface.cpp プロジェクト: AmirAbrams/haiku
static status_t
ext2_remove_vnode(fs_volume* _volume, fs_vnode* _node, bool reenter)
{
	TRACE("ext2_remove_vnode()\n");
	Volume* volume = (Volume*)_volume->private_volume;
	Inode* inode = (Inode*)_node->private_node;
	ObjectDeleter<Inode> inodeDeleter(inode);

	if (!inode->IsDeleted())
		return B_OK;

	TRACE("ext2_remove_vnode(): Starting transaction\n");
	Transaction transaction(volume->GetJournal());

	if (!inode->IsSymLink() || inode->Size() >= EXT2_SHORT_SYMLINK_LENGTH) {
		TRACE("ext2_remove_vnode(): Truncating\n");
		status_t status = inode->Resize(transaction, 0);
		if (status != B_OK)
			return status;
	}

	TRACE("ext2_remove_vnode(): Removing from orphan list\n");
	status_t status = volume->RemoveOrphan(transaction, inode->ID());
	if (status != B_OK)
		return status;

	TRACE("ext2_remove_vnode(): Setting deletion time\n");
	inode->Node().SetDeletionTime(real_time_clock());

	status = inode->WriteBack(transaction);
	if (status != B_OK)
		return status;

	TRACE("ext2_remove_vnode(): Freeing inode\n");
	status = volume->FreeInode(transaction, inode->ID(), inode->IsDirectory());

	// TODO: When Transaction::Done() fails, do we have to re-add the vnode?
	if (status == B_OK)
		status = transaction.Done();

	return status;
}
コード例 #16
0
bool MailingList::ProcessEmailFile(std::string emailfilepathstr)
{
	/*
		Check if sender of email is authorised to post to this list, if not return true and caller will delete file
		else copy it to an outgoing email with relevent header changes, queue og mail for delivery
		and return true so caller will delete file.
		Any errors return false
	*/
	
	
	BFile* bfile = new BFile(emailfilepathstr.c_str(),B_READ_WRITE);
	
	if (bfile->InitCheck() != B_NO_ERROR)
	{
		LogError("ERROR: Could not process an incoming email. BFile::InitCheck was false");
		return false;
	}

	IncomingMail* ICMail= new IncomingMail(bfile,this);
	if (ICMail->InitCheck()==false)
	{
		LogError("ERROR: Could not process an incoming email. File read failed. IncomingMail::InitCheck was false");
		return false;
	}
	
	if (fLogSuccesses)
	{
		LogError("INFO: Processing an email file from "+ICMail->GetSendersAddr());
	}
	
	
	int32 authstatus=1;
	
	/*
		Return vals from external auth prog are 
		0=Authorised
		1=Error
		2=Not Authorsed - bounce msg
		3=Not Authorised - silently discard
		
		This func should return false if val is 1, thus ensuring the incoming file is not deleted and will be re-processed later
		for all other values it should return true, indicating that the incoming file can be deleted
	*/
	int32 arg_c = 4; //no of args passed in arg_v
	extern char **environ; //env variables
	char **arg_v;
	arg_v = (char **) malloc(sizeof(char*) * (arg_c+1)); //array must hold arg_c elements + a terminating null
	
	std::stringstream epochsecs;
	epochsecs << real_time_clock(); //secs now since unix epoch
	int filenamecounterInt=0; //will be incremented until we get a unique filename string
	bool nonuniquefilename=true;
	BEntry tempFileBEntry;
	std::string tempFilePath;
	do
	{
		filenamecounterInt++;
		std::stringstream filenamecounter;
		filenamecounter << filenamecounterInt;
		MailMistressApplication* app=(MailMistressApplication*) be_app;
		tempFilePath=app->GetTempDirPath()+fListICAddress+"--"+ICMail->GetSendersAddr()+"--"+epochsecs.str()+filenamecounter.str();
		//test if tempFilePath already exists
		tempFileBEntry.SetTo(tempFilePath.c_str());
		BFile tempFileBFile;
		status_t tempFileResult=tempFileBFile.SetTo(&tempFileBEntry,B_READ_WRITE|B_FAIL_IF_EXISTS|B_CREATE_FILE); //fails if already exists
		if (tempFileResult==B_FILE_EXISTS)
		{
			nonuniquefilename=true;	
		}
		else if (tempFileResult==B_NO_ERROR)
		{
			nonuniquefilename=false;
			tempFileBFile.Unset(); //close file
		}
		else
		{
			//error
			bfile->Unset();
			//delete ICMail obj
			delete ICMail;
			delete bfile;

			return false;
		}
		
	}while(nonuniquefilename);
	
	
	arg_v[0]=strdup(fAuthProgPath.c_str()); //path to exe
	arg_v[1]=strdup((ICMail->GetSendersAddr()).c_str()); //senders email addr
	arg_v[2]=strdup(tempFilePath.c_str()); //path to temp file
	arg_v[3]=strdup(fListICAddress.c_str()); //list IC address
	arg_v[4]=NULL;
	
	thread_id authprog_team;
	authprog_team=load_image(arg_c,(const char**)arg_v,(const char**)environ);
	free(arg_v);
	wait_for_thread(authprog_team,&authstatus);
	//if authstatus==0 then temp file will now contain all recipient email addresses one per line
	
	if (authstatus==0)
	{
		//send to recipients in temp file
		if (DistributeEmail(ICMail,tempFilePath))
		{
				//delete temp file
				tempFileBEntry.Remove();
				
				//delete ICMail obj
				delete ICMail;
				
				//close orig email file
				bfile->Unset();
				delete bfile;
				return true;
		}
		else
		{
				//delete temp file
				tempFileBEntry.Remove();
				
				//delete ICMail obj
				delete ICMail;
				
				//close orig email file
				bfile->Unset();
				delete bfile;
			
				return false;
		}
	}
	else if (authstatus==2)
	{
			LogError("INFO: Auth status 2 -- Bouncing to "+ICMail->GetSendersAddr());
			BMailMessage* ogmail;
			ogmail= new BMailMessage();
			ogmail->AddHeaderField(B_MAIL_TO,(ICMail->GetSendersAddr()).c_str());
			ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
			std::string bouncesubject=std::string("Undelivered mail: Your message to ");
			bouncesubject=bouncesubject+fListName+" was rejected";
			ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
			ogmail->AddHeaderField("X-Mailer: ",(fApp->GetAppName()).c_str());
    	  	ogmail->AddContent(fUnauthorisedBounceMsgContents.c_str(),strlen(fUnauthorisedBounceMsgContents.c_str()));
			ogmail->Send();
			delete ogmail;
	}
	else if (authstatus==3)
	{
			LogError("INFO: Auth status 3 -- Silently discarding email from "+ICMail->GetSendersAddr());	
			
	}
	
	//delete temp file
	tempFileBEntry.Remove();
	
	if ( (authstatus==2) || (authstatus==3)  )
	{
		//ok so return true to delete incoming file
		delete ICMail;
		bfile->Unset();
		delete bfile;
		
		return true;	
	}
	else
	{
		//error occured so return false and incoming file will be kept for reprocessing later
		LogError("ERROR: Auth status 1 (or other error value). Either the autentication program failed to run or it encountered an error itself");
		delete ICMail;
		bfile->Unset();
		delete bfile;
	
		return false;	
	}
	
}
コード例 #17
0
ファイル: Shisen.cpp プロジェクト: HaikuArchives/BShisen
Shisen::Shisen():
	BApplication("application/x-vnd.KWS-BShisen")
{
system_info info;
union split sp;
app_info app;

#ifdef USE_YLANGUAGE
	Language.SetName("English");
	if (Language.InitCheck() != B_OK)
		printf("error loading language file (English\n");
		
	BuildLanguageList();
#endif

	REGISTERED = false;
	NAG = false;
	
	get_system_info(&info);get_system_info(&info);
	
//	if (info.id[0] && info.id[1]) // P3 ?
//	{
//		sp.i32[0] = info.id[0];
//		sp.i32[1] = info.id[1];
		KEY = sp.i64;
//	}
//	else	// make a KEY from the CPU TYPE & the speed
//	{
//		KEY = info.cpu_clock_speed;
//		KEY |= info.cpu_revision;
//	}
	
	// sanity check
	if (!KEY) KEY = 0xbebebebe;
	
	//printf("key is %lx\n", KEY);
	
	
	/*
	 * 1) Check the creation time
	 * 2) Check the last accessed time
	 * 3) subtract
	 * if > 3 days, nag++
	 */
	// check ~/config/settings/BShisen_prefs

	BPath path;
	BEntry entry;
	
	if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK
		&& path.Append(PREFS_FILE_NAME, true) == B_OK
		&& entry.SetTo(path.Path(), true) == B_OK)
	{
		time_t t_t = 0;
		time_t c_t;
		
		if (entry.GetCreationTime(&c_t) == B_OK)
		{
			//ok, file exists.  Check the creation date & see if it was > 7 days ago
			t_t = (time_t)real_time_clock();
			
			if (t_t > c_t)
			{
				t_t -= c_t;
				
				// t_t == # of secs between when file was created & now
				
				if (t_t > 7 * 24 * 60 * 60) NAG = true;
			}
		}
	}	



#if 0	
	if (GetAppInfo(&app) == B_OK)
	{
		BEntry entry;
		struct stat st;
		time_t t_t;
		
		entry.SetTo(&app.ref, true);
		entry.GetStat(&st);
	
		t_t = st.st_atime - st.st_ctime;

		if (t_t > 5 * 24 * 60 * 60)
			NAG = true;
	}
#endif

	game = new GameWindow;
	game->Show();	
}
コード例 #18
0
void
DownloadProgressView::_UpdateStatusText()
{
	fInfoView->SetText("");
	BString buffer;
	if (sShowSpeed && fBytesPerSecond != 0.0) {
		// Draw speed info
		char sizeBuffer[128];
		buffer = "(";
		// Get strings for current and expected size and remove the unit
		// from the current size string if it's the same as the expected
		// size unit.
		BString currentSize = string_for_size((double)fCurrentSize, sizeBuffer,
			sizeof(sizeBuffer));
		BString expectedSize = string_for_size((double)fExpectedSize, sizeBuffer,
			sizeof(sizeBuffer));
		int currentSizeUnitPos = currentSize.FindLast(' ');
		int expectedSizeUnitPos = expectedSize.FindLast(' ');
		if (currentSizeUnitPos >= 0 && expectedSizeUnitPos >= 0
			&& strcmp(currentSize.String() + currentSizeUnitPos,
				expectedSize.String() + expectedSizeUnitPos) == 0) {
			currentSize.Truncate(currentSizeUnitPos);
		}
		buffer << currentSize;
		buffer << " of ";
		buffer << expectedSize;
		buffer << ", ";
		buffer << string_for_size(fBytesPerSecond, sizeBuffer,
			sizeof(sizeBuffer));
		buffer << "/s)";
		float stringWidth = fInfoView->StringWidth(buffer.String());
		if (stringWidth < fInfoView->Bounds().Width())
			fInfoView->SetText(buffer.String());
		else {
			// complete string too wide, try with shorter version
			buffer << string_for_size(fBytesPerSecond, sizeBuffer,
				sizeof(sizeBuffer));
			buffer << "/s";
			stringWidth = fInfoView->StringWidth(buffer.String());
			if (stringWidth < fInfoView->Bounds().Width())
				fInfoView->SetText(buffer.String());
		}
	} else if (!sShowSpeed && fCurrentSize < fExpectedSize) {
		double totalBytesPerSecond = (double)(fCurrentSize
				- fEstimatedFinishReferenceSize)
			* 1000000LL / (system_time() - fEstimatedFinishReferenceTime);
		double secondsRemaining = (fExpectedSize - fCurrentSize)
			/ totalBytesPerSecond;
		time_t now = (time_t)real_time_clock();
		time_t finishTime = (time_t)(now + secondsRemaining);

		tm _time;
		tm* time = localtime_r(&finishTime, &_time);
		int32 year = time->tm_year + 1900;

		char timeText[32];
		time_t secondsPerDay = 24 * 60 * 60;
		// TODO: Localization of time string...
		if (now < finishTime - secondsPerDay) {
			// process is going to take more than a day!
			sprintf(timeText, "%0*d:%0*d %0*d/%0*d/%ld",
				2, time->tm_hour, 2, time->tm_min,
				2, time->tm_mon + 1, 2, time->tm_mday, year);
		} else {
			sprintf(timeText, "%0*d:%0*d",
				2, time->tm_hour, 2, time->tm_min);
		}

		BString buffer1("Finish: ");
		buffer1 << timeText;
		finishTime -= now;
		time = gmtime(&finishTime);

		BString buffer2;
		if (finishTime > secondsPerDay) {
			int64 days = finishTime / secondsPerDay;
			if (days == 1)
				buffer2 << "Over 1 day";
			else
				buffer2 << "Over " << days << " days";
		} else if (finishTime > 60 * 60) {
			int64 hours = finishTime / (60 * 60);
			if (hours == 1)
				buffer2 << "Over 1 hour";
			else
				buffer2 << "Over " << hours << " hours";
		} else if (finishTime > 60) {
			int64 minutes = finishTime / 60;
			if (minutes == 1)
				buffer2 << "Over 1 minute";
			else
				buffer2 << minutes << " minutes";
		} else {
			if (finishTime == 1)
				buffer2 << "1 second";
			else
				buffer2 << finishTime << " seconds";
		}

		buffer2 << " left";

		buffer = "(";
		buffer << buffer1 << " - " << buffer2 << ")";

		float stringWidth = fInfoView->StringWidth(buffer.String());
		if (stringWidth < fInfoView->Bounds().Width())
			fInfoView->SetText(buffer.String());
		else {
			// complete string too wide, try with shorter version
			buffer = "(";
			buffer << buffer1 << ")";
			stringWidth = fInfoView->StringWidth(buffer.String());
			if (stringWidth < fInfoView->Bounds().Width())
				fInfoView->SetText(buffer.String());
		}
	}
}
コード例 #19
0
ファイル: date.cpp プロジェクト: svn2github/Themis
int32 Date::ParseDate(const char *date)
{
	if (date==NULL)
		return B_ERROR;
		time_t now = time(NULL);
		return parsedate(date,now);
//		printf("Date as received: %s\n",date);
	/*
		We need to handle folding whitespace as defined in RFC 2822, so lets take
		care of that first.
	*/
	int32 length=strlen(date);
	char *copy=new char[length+1];
	memset(copy,0,length+1);
	strcpy(copy,date);
	int32 fws_count=0;
	char *fws_p=NULL;
	fws_p=strstr(copy,"\r\n");
	while(fws_p!=NULL)
	{
		if (isspace(*(fws_p+2)))
		{
			fws_count++;
			memmove(fws_p,fws_p+2,strlen(fws_p+2)+1);//replace the fws with three spaces instead
		}
		fws_p=strstr(fws_p+2,"\r\n");
	}
//	printf("%ld instances of folding whitespace encountered\n",fws_count);
//	printf("modified copy of date string: %s\n",copy);
	/*
		We also need to handle comments as defined in RFC 2822.
	*/
	char *open_p=strchr(copy,'('),*close_p=NULL;
	int32 comment_count=0;
	while (open_p!=NULL)
	{
		close_p=strchr(open_p,')');
		if (close_p!=NULL)
		{
			comment_count++;
			int32 remainder=strlen(close_p+1);
			memmove(open_p,close_p+1,remainder+1);
		}
		open_p=strchr(open_p,'(');
	}
	/*
		Some date strings used in cookies have the nerve to have hyphens between
		the day, month, and year... The audacity! Convert them to space characters!
	*/
	char *hyphen=strchr(copy,'-');
	while (hyphen!=NULL)
	{
		*hyphen=0x20;
		hyphen=strchr(hyphen,'-');
	}
//	printf("%ld comments encountered\n",comment_count);
//	printf("modified copy of date string: %s\n",copy);
	/*
		Now proceed to analyze the date...
	*/
	char *start_p=copy,*comma=strchr(copy,',');
	//If we have a comma, that means there's a day of the week expression starting things off. Skip it.
	if (comma!=NULL)
		start_p=(comma+1);
	/*
		There are five key sections that will need to be isolated and analyzed:
		1	Day of the month.
		2	Month of the year.
		3	Year.
		4	Time of day.
		5	Time zone.
		So divide the string up into it's sections.
	*/
	char *sections[5]={NULL,NULL,NULL,NULL,NULL};
	int32 lengths[5]={0,0,0,0,0};
	int32 section_counter=0;
	for (;section_counter<5; )
	{
		if ((*start_p)==(char)NULL)
			break;
		if (isspace(*start_p))
		{
			start_p++;
			continue;
		}
		sections[section_counter]=start_p;
		while(!isspace(*start_p))
		{
			if ((*start_p)==(char)NULL)
				break;
			start_p++;
			lengths[section_counter]++;
		}
//		printf("section %d is %d bytes long\n",section_counter+1,lengths[section_counter]);
		section_counter++;
	}
//	char *sn[5]={"Day","Month","Year","Time","Time Zone"};
	char *value;
	/*
		Move the data into a time structure.
	*/
	struct tm tstruct;
	for (int i=0; i<5; i++)
	{
		value=new char[lengths[i]+1];
		memset(value,0,lengths[i]+1);
		strncpy(value,sections[i],lengths[i]);
//		printf("\t%s:\t%s\n",sn[i],value);
		switch(i)
		{
			case 0:
			{
				tstruct.tm_mday=atoi(value);
			}break;
			case 1:
			{
				if (strcasecmp(value,"jan")==0)
					tstruct.tm_mon=0;
				if (strcasecmp(value,"feb")==0)
					tstruct.tm_mon=1;
				if (strcasecmp(value,"mar")==0)
					tstruct.tm_mon=2;
				if (strcasecmp(value,"apr")==0)
					tstruct.tm_mon=3;
				if (strcasecmp(value,"may")==0)
					tstruct.tm_mon=4;
				if (strcasecmp(value,"jun")==0)
					tstruct.tm_mon=5;
				if (strcasecmp(value,"jul")==0)
					tstruct.tm_mon=6;
				if (strcasecmp(value,"aug")==0)
					tstruct.tm_mon=7;
				if (strcasecmp(value,"sep")==0)
					tstruct.tm_mon=8;
				if (strcasecmp(value,"oct")==0)
					tstruct.tm_mon=9;
				if (strcasecmp(value,"nov")==0)
					tstruct.tm_mon=10;
				if (strcasecmp(value,"dec")==0)
					tstruct.tm_mon=11;
			}break;
			case 2:
			{
				if (lengths[i]==4)
				{
					tstruct.tm_year=atol(value)-1900;
				} else
				{
				
					int16 year=atol(value);
					/*
						The following is more technically correct, but in truth
						it is no different than just doing tstruct.tm_year=atol(value)
						provided that the length of the year is less than 4 but greater
						than 0.
					*/
					if ((lengths[i]==2) && (year<50) && (year>=0))
						year+=2000;
					else
						if (((lengths[i]==2) && (year>=50) && (year<100)) || (lengths[i]==3))
							year+=1900;
					tstruct.tm_year=year-1900;
				}
			}break;
			case 3:
			{
				char *time_array[3];
				time_array[0]=strtok(value,":");
				time_array[1]=strtok(NULL,":");
				time_array[2]=strtok(NULL,":");
//				printf("Hour: %s\nMinute: %s\nSeconds: %s\n",time_array[0],time_array[1],time_array[2]);
				tstruct.tm_hour=atoi(time_array[0]);
				tstruct.tm_min=atoi(time_array[1]);
				if (time_array[2]!=NULL)
					tstruct.tm_sec=atoi(time_array[2]);
			}break;
			case 4:
			{
				/*
					Adjust the time in the structure based on the time zone information to
					get GMT time...
				*/
				if ((ispunct(value[0]) && (strpbrk(value,"-+")==value)) && (strlen(value)==5))
				{
//					printf("Numeric time zone!\n");
					bool positive=false;
					int32 minutes=0,hours=0, zone=0;
					if (value[0]=='+')
						positive=true;
					zone=atoi((value+1));
					hours=zone/100;
					minutes=zone%100;
					printf("This time is GMT %c %d hours %d minutes\n",value[0],hours,minutes);
					
					if (positive)
					{//if the time zone is positive, we need to subtract to get gmt
						tstruct.tm_gmtoff=-(3600*hours+60*minutes);
					} else
					{//if the time zone is negative, we need to add to get gmt
						tstruct.tm_gmtoff=(3600*hours+60*minutes);
					}
					
				} else
				{
//					printf("String time zone!\n");
					int32 offset=0,local_offset=0;
					time_t current_time=real_time_clock();
					struct tm *gmt=localtime(&current_time);
					if (gmt->tm_gmtoff<0)
						local_offset=-gmt->tm_gmtoff;
					else
						local_offset=gmt->tm_gmtoff;
					if (gmt->tm_isdst)
						local_offset+=3600;
//					printf("GMT offset of local machine: %d\n",gmt->tm_gmtoff);
					if ((strcasecmp("GMT",value)==0) || (strcasecmp("UT",value)==0))
					{//Then we need to find the GMT offset of the local machine
						printf("(GMT) local offset: %ld\toffset: %ld\n",local_offset,offset);
						local_offset-=3600;
					}
					/*
						Add more time zone strings and values as time and sanity permit.
					*/
					if (strcasecmp("edt",value)==0)//US Eastern Daylight Time
						offset=0x3840;
					if (strcasecmp("est",value)==0)//US Eastern Standard Time
						offset=0x4650;
					if (strcasecmp("cdt",value)==0)//US Central Daylight Time
						offset=0x4650;
					if (strcasecmp("cst",value)==0)//US Central Standard Time
						offset=0x5460;
					if (strcasecmp("mdt",value)==0)//US Mountain Daylight Time
						offset=0x5460;
					if (strcasecmp("mst",value)==0)//US Mountain Standard Time
						offset=0x6270;
					if (strcasecmp("pdt",value)==0)//US Pacific Daylight Time
						offset=0x6270;
					if (strcasecmp("pst",value)==0)//US Pacific Standard Time
						offset=0x7080;
//						printf("local offset: %d\nother offset: %d\n",local_offset,offset);
//					if (offset==0)
//						offset=local_offset;
					offset=local_offset-offset;
//					printf("difference: %d\n",offset);
						int32 hours=offset/3600, minutes=(offset%3600)/60;
						tstruct.tm_hour-=hours;
						tstruct.tm_min-=minutes;
					
				}
			}break;
		}
		memset(value,0,lengths[i]+1);
		delete value;	
	}
	time_t ttime=mktime(&tstruct);
	ttime=mktime(localtime(&ttime));
//	printf("ctime() (localtime): %s\n",ctime(&ttime));
	char dt[100];
	memset(dt,0,100);
	strftime(dt,99,"%a %B %d, %Y %H:%M:%S %Z",&tstruct);
	printf("strftime (localtime): %s (%s)\n",dt,asctime(&tstruct));
	memset(dt,0,100);
//	struct tm *gmt=gmtime(&ttime);
//	strftime(dt,99,"%a %B %d, %Y %H:%M:%S %Z",gmt);
//	printf("strftime (GMT): %s\n",dt);
	memset(copy,0,length+1);
	delete copy;
	return ttime;
}
コード例 #20
0
ファイル: date.cpp プロジェクト: svn2github/Themis
int32 Date::Age(void)
{
	return (real_time_clock()-unix_timestamp);
}
コード例 #21
0
ファイル: date.cpp プロジェクト: svn2github/Themis
void Date::Init(void)
{
	unix_timestamp=real_time_clock();
}
コード例 #22
0
ファイル: SourceTypeC.cpp プロジェクト: HaikuArchives/Paladin
bool
SourceFileC::CheckNeedsBuild(BuildInfo &info, bool check_deps)
{
	// The checks for a file needing to be built:
	// 1) Build flag != BUILD_MAYBE => return result
	// 2) Object file missing
	// 3) Source mod time > object mod time
	// 4) Dependency file needs build

	
	// The fast stuff
	if (!info.objectFolder.GetFullPath())
	{
		STRACE(2,("CheckNeedsBuild: empty file path\n"));
		return false;
	}
	
	if (BuildFlag() == BUILD_YES)
	{
		STRACE(2,("%s::CheckNeedsBuild: build flag == YES\n",GetPath().GetFullPath()));
		return true;
	}
	
	// Object file existence
	BString objname(GetPath().GetBaseName());
	objname << ".o";
	
	DPath objpath(info.objectFolder);
	objpath.Append(objname);
	if (!BEntry(objpath.GetFullPath()).Exists())
	{
		STRACE(2,("%s::CheckNeedsBuild: object doesn't exist\n",GetPath().GetFullPath()));
		return true;
	}
	
	// source vs object mod time
	struct stat objstat;
	if (GetStat(objpath.GetFullPath(),&objstat) != B_OK)
	{
		STRACE(2,("%s::CheckNeedsBuild: couldn't stat object\n",GetPath().GetFullPath()));
		return false;
	}
	
	// Fix mod times set into the future
	time_t now = real_time_clock();
	if (GetModTime() > now)
	{
		BNode node(GetPath().GetFullPath());
		node.SetModificationTime(now);
	}
	
	if (GetModTime() > objstat.st_mtime)
	{
		STRACE(2,("%s::CheckNeedsBuild: file time more recent than object time\n",
				GetPath().GetFullPath()));
		return true;
	}
	
	if (!check_deps)
	{
		STRACE(2,("%s::CheckNeedsBuild: dependency checking disabled for call\n",
				GetPath().GetFullPath()));
		return false;
	}
	
	// Dependency check
	BString str(GetDependencies());
	if (str.CountChars() < 1)
	{
		STRACE(2,("%s::CheckNeedsBuild: initial dependency update\n",
				GetPath().GetFullPath()));
		UpdateDependencies(info);
		str = GetDependencies();
	}
	
	if (str.CountChars() > 0)
	{
		char *pathstr;
		char depString[str.Length() + 1];
		sprintf(depString,"%s",str.String());

		pathstr = strtok(depString,"|");
		while (pathstr)
		{
			BString filename(DPath(pathstr).GetFileName());
			if (filename.Compare(GetPath().GetFileName()) != 0)
			{
				DPath depPath(FindDependency(info,filename.String()));
				if (!depPath.IsEmpty())
				{
					struct stat depstat;
					if (GetStat(depPath.GetFullPath(),&depstat) == B_OK &&
						depstat.st_mtime > objstat.st_mtime)
					{
						STRACE(2,("%s::CheckNeedsBuild: dependency %s was updated\n",
								GetPath().GetFullPath(),depPath.GetFullPath()));
						return true;
					}
				}
			}
			pathstr = strtok(NULL,"|");
		}
	}
	
	return false;
}
コード例 #23
0
ファイル: ntp.cpp プロジェクト: veer77/Haiku-services-branch
uint32
seconds_since_1900(void)
{
	return kSecondsBetween1900And1970 + real_time_clock();
}
コード例 #24
0
bool MailingList::DistributeEmail(IncomingMail* ICMail, std::string ogaddrfilepath)
{
	
	//send ICMail to every address in ogaddrfilepath
	std::vector<std::string> recipients;
	BFile recipientlistbfile;
	status_t filestatus=recipientlistbfile.SetTo(ogaddrfilepath.c_str(),B_READ_ONLY);
	if (filestatus!=B_NO_ERROR)
	{
		LogError("ERROR: Could not read temp file from authentication program - the file could not be opened. Does it exist?");
		return false;	
	}
		off_t bytes; //size of file
		if (recipientlistbfile.GetSize(&bytes) == B_NO_ERROR)
		{
		
			char* buff = new char[bytes];
			off_t bytesread=recipientlistbfile.Read(buff,bytes);
			if (bytesread > 0)
			{
				//file read ok
	
				std::string addr="";
	
				for (int x=0; x < bytesread; x++)
				{
					if (buff[x]!='\n')
					{
						addr=addr+buff[x];
					}
					else
					{
						recipients.push_back(addr);
						addr="";	
					}
				}	
				delete buff;
			}
			else
			{
				LogError("ERROR: Could not read temp file from authentication program - the file was empty");
				delete buff;
				return false;	
			}
		}
		else
		{
			LogError("ERROR: Could not read temp file from authentication program -- could not determine file size");
			return false;	
		}
		
		ICMail->AddSubjectPrefix(fListSubjectPrefix); //fListSubjectPrefix will be null str if not defined in conf file
		ICMail->CleanHeaders(); //clean & setup headers ready for sending message out to recipients
		ICMail->AdjustReplyTo(fForceReplyToList); //set reply to to either sender or list IC address
		
		//if List-Xyz header values were set in conf file we need to set them in msg
		if (fListOwner!="")
		{
			ICMail->SetListOwnerHeader(fListOwner);
		}
		if (fListHelp!="")
		{
			ICMail->SetListHelpHeader(fListHelp);
		}
		if (fListArchive!="")
		{
			ICMail->SetListArchiveHeader(fListArchive);
		}
		if (fListSubscribe!="")
		{
			ICMail->SetListSubscribeHeader(fListSubscribe);
		}
		if (fListUnSubscribe!="")
		{
			ICMail->SetListUnSubscribeHeader(fListUnSubscribe);
		}
	//call GetFromField to get email address in case we need to bounce msg 

	std::string ICsendersAddrField=ICMail->GetSendersAddr(); //returns null string if unable to find
	//at present ICsendersAddrField now has address in form user@domain NOT <user@domain> is this in line with RFC spec?
	


	if (ICMail->CheckIfPlainTextCriteriaPassed(fPlainTextOnly)==false)
	{
		//bounce
		if (fPlainTextOnly=='Y')
		{
				//bounce to sender
				LogError("INFO: Incoming email not text/plain and non plain text messages are not allowed. Bounced to "+ICsendersAddrField);
				BMailMessage* ogmail;
				ogmail= new BMailMessage();
				ogmail->AddHeaderField(B_MAIL_TO,ICsendersAddrField.c_str());
				ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
				std::string bouncesubject=std::string("Undelivered mail: Your message to ");
				bouncesubject=bouncesubject+fListName+" was rejected";
				ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
				std::string xmailer=(fApp->GetAppName())+" mailing list server for Haiku";
				ogmail->AddHeaderField("X-Mailer: ",xmailer.c_str());
				ogmail->AddHeaderField("precedence: ","list");
				std::string bouncecontent="Your message to "+fListName+" was rejected because this list only accepts plain text messages. Make sure your email program is not creating HTML or Rich Text emails and that there are no attached files.";
				bouncecontent=bouncecontent+"\n\nThis is an automated reply sent from the "+fApp->GetAppName()+" for Haiku server at "+fListICAddress;
    			ogmail->AddContent(bouncecontent.c_str(),strlen(bouncecontent.c_str()));
				ogmail->Send();
				delete ogmail;
		}
		else
		{
				//fPlainTextOnly must be 'H'
				//bounce to sender
				LogError("INFO: Incoming email not HTML or plain text and non text messages are not allowed. Bounced to "+ICsendersAddrField);
				BMailMessage* ogmail;
				ogmail= new BMailMessage();
				ogmail->AddHeaderField(B_MAIL_TO,ICsendersAddrField.c_str());
				ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
				std::string bouncesubject=std::string("Undelivered mail: Your message to ");
				bouncesubject=bouncesubject+fListName+" was rejected";
				ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
				std::string xmailer=(fApp->GetAppName())+" mailing list server for Haiku";
				ogmail->AddHeaderField("X-Mailer: ",xmailer.c_str());
				ogmail->AddHeaderField("precedence: ","list");
				std::string bouncecontent="Your message to "+fListName+" was rejected because this list only accepts HTML or plain text messages. Make sure that there are no attached files.";
				bouncecontent=bouncecontent+"\n\nThis is an automated reply sent from the "+fApp->GetAppName()+" for Haiku server at "+fListICAddress;
    			ogmail->AddContent(bouncecontent.c_str(),strlen(bouncecontent.c_str()));
				ogmail->Send();
				delete ogmail;
		}
		return true;
	}

	
	if (ICMail->GetICFileSize() > fMaxContentBytes)
	{
		//msg too big bounce to sender
		LogError("INFO: Incoming email too big. Bounced to "+ICsendersAddrField);
		BMailMessage* ogmail;
		ogmail= new BMailMessage();
		ogmail->AddHeaderField(B_MAIL_TO,ICsendersAddrField.c_str());
		ogmail->AddHeaderField(B_MAIL_FROM,fListOGEnvelopeAddressFromAddress.c_str());
		std::string bouncesubject=std::string("Undelivered mail: Your message to ");
		bouncesubject=bouncesubject+fListName+" was rejected";
		ogmail->AddHeaderField(B_MAIL_SUBJECT,bouncesubject.c_str());
		std::string xmailer=(fApp->GetAppName())+" mailing list server for Haiku";
		ogmail->AddHeaderField("X-Mailer: ",xmailer.c_str());
		ogmail->AddHeaderField("precedence: ","list");
		stringstream converter;
		converter << fMaxContentBytes << " bytes, your message was " << ICMail->GetICFileSize() << " bytes";
		std::string toobigcontent="Your message to "+fListName+" is too big and was rejected. Maximum allowable size for this list is "+converter.str();
		toobigcontent=toobigcontent+"\n\nThis is an automated reply sent from the "+fApp->GetAppName()+" for Haiku server at "+fListICAddress;
    	ogmail->AddContent(toobigcontent.c_str(),strlen(toobigcontent.c_str()));
		ogmail->Send();
		delete ogmail;
		return true;
	}



	//setup a temp file to store the modified og msg
	std::stringstream epochsecs;
	epochsecs << real_time_clock(); //secs now since unix epoch
	int filenamecounterInt=0; //will be incremented until we get a unique filename string
	bool nonuniquefilename=true;
	BEntry tempFileBEntry;
	std::string tempFilePath;
	BFile* tempFileBFile = new BFile();
	do
	{
		filenamecounterInt++;
		std::stringstream filenamecounter;
		filenamecounter << filenamecounterInt;
		tempFilePath=fApp->GetTempDirPath()+fListICAddress+"--"+epochsecs.str()+filenamecounter.str();
		//test if tempFilePath already exists
		tempFileBEntry.SetTo(tempFilePath.c_str());
		status_t tempFileResult=tempFileBFile->SetTo(&tempFileBEntry,B_READ_WRITE|B_FAIL_IF_EXISTS|B_CREATE_FILE); //fails if already exists
		if (tempFileResult==B_FILE_EXISTS)
		{
			nonuniquefilename=true;	
		}
		else if (tempFileResult==B_NO_ERROR)
		{
			nonuniquefilename=false;
			
		}
		else
		{
			//error
			LogError("ERROR: Could not create temp file to store outgoing email");
			return false;
		}
		
	}while(nonuniquefilename);

	//Write modified msg into temp file

	ICMail->WriteToFile(tempFileBFile);



	//store senders addr so we can log it later
	std::string sender="";
	//Send out modified msg in temp file to all recipients
	for (int x=0; x< recipients.size(); x++)
	{
		std::string recipient=recipients[x];
		
		BEmailMessage* ogmail;
		ogmail= new BEmailMessage(tempFileBFile);
    	ogmail->SetTo(recipient.c_str());
    	sender=std::string(ogmail->From());
    	//1st version of send indicates whether to change the From: field to the specified account (requires modified mailkit)
		ogmail->SendViaAccountWithFromPreset(fListOGEnvelopeAddressFromAddress.c_str());
		//ogmail->SendViaAccount(fListOGEnvelopeAddressFromAddress.c_str());
		ogmail->Send(true);
		delete ogmail;
		
	}
	tempFileBFile->Unset(); //close file
	delete tempFileBFile; //delete obj
	//archive msg if needed
	bool archived=false;
	if (fArchivePath!="")
	{
			
			BDirectory dir;
			if ( dir.SetTo(fArchivePath.c_str()) !=B_OK )
			{
				LogError("ERROR: Could not archive message. Check archive folder exists and is writable");
			}
			else
			{
				if ( tempFileBEntry.MoveTo(&dir) !=B_NO_ERROR)
				{
					LogError("ERROR: Could not archive message. Check archive folder exists and is writable");
				}
				else
				{
					archived=true;	
				}
			}
			
	}
	if (archived==false)
	{
		//if archived  then the file was moved so we dont need to delete the original
		tempFileBEntry.Remove();//remove file from filesystem	
	}
	
	stringstream numRecipients;
	numRecipients << recipients.size();
	
	if ( (fLogSuccesses) && (recipients.size()>0)  )
	{
		//if we recipients.size() was 0 sender var is null str as its set in the distribution loop
		LogError("INFO: Successfully distributed an email to "+numRecipients.str()+" recipients from "+sender);
	}
	return true;
}
コード例 #25
0
ファイル: select_test2.c プロジェクト: SummerSnail2014/haiku
int main(int argc, char **argv)
{
	int s, f;
	int rv;
	struct fd_set fdr, fdw, fde;
	struct timeval tv;
	int32 rtc;
	char path[PATH_MAX];
		
	test_banner("Select Test #2");
			
	s = socket(AF_INET, SOCK_DGRAM, 0);
	if (s < 0)
		err(s, "Socket creation failed");

	getcwd(path, PATH_MAX);
	sprintf(path, "%s/select_test2.c", path);
	f = open(path, O_RDWR);

	if (f > 0 && s > 0)	{
		printf("\nsocket and fd created.\n");
	} else {
		err(-1, "Failed to create socket or fd\n");
	}
	
	FD_ZERO(&fdr);
	FD_SET(s, &fdr);
	FD_ZERO(&fdw);
	FD_SET(s, &fdw);
	FD_ZERO(&fde);
	FD_SET(s, &fde);
	
	tv.tv_sec = 5;
	tv.tv_usec = 0;
	printf("\nTest1\n=====\n\n");	
	printf("Trying with timeval (5 secs)...\n");
	rtc = real_time_clock();
	rv = select(s + 1, &fdr, NULL, &fde, &tv);
	rtc = real_time_clock() - rtc;
	printf("select gave %d (expecting 0) in %ld seconds\n", rv, rtc);

	FD_ZERO(&fdr);
	FD_SET(s, &fdr);
	FD_SET(f, &fdr);
	FD_ZERO(&fdw);
	FD_SET(s, &fdw);
	FD_ZERO(&fde);
	FD_SET(s, &fde);
	
	printf("\nTest2\n=====\n\n");
	printf("Trying without timeval and both sockets and files...\n");
	rv = select(f +1, &fdr, NULL, NULL, NULL);
	printf("select gave %d (expecting 2)\n", rv);
	
	if (rv > 0) {
		if (FD_ISSET(s, &fdr))
			printf("Data to read\n");
		if (FD_ISSET(s, &fdw))
			printf("OK to write\n");
		if (FD_ISSET(s, &fde))
			printf("Exception!\n");
		if (FD_ISSET(f, &fdr))
			printf("File is readable!\n");
	} else if (rv == 0) {
		printf("Timed out??? huh?!\n");
	} else {
		printf("errno = %d [%s]\n", errno, strerror(errno));
	}
	
	closesocket(s);
	close(f);
	
	printf("Test complete.\n");

	return (0);
}
コード例 #26
0
	void SetLastSemopTime()
	{
		fLastSemopTime = real_time_clock();
	}