搜尋
首頁後端開發php教程探讨php中error_log函数输出内容的原子性问题_PHP教程

探讨php中error_log函数输出内容的原子性问题

前几天跟同事讨论如何在一次login php调用中保证error_log输出的日志都有唯一的标识头,结论是玩家帐号+当前时间+随机数,在我们当前用户量级条件下应该是满足需求的,当然,这并不是本文讨论的重点。

在确定这个简单的方案之后,我在想两个问题,也是今天本文讨论的重点:

1.error_log调用是否可以保证输出内容是完整的?

2.如果是完整的,那么是怎样保证的?

求证开始了,起初以为error_log调用中会对目标文件加文件锁,直接看源码(php5.6.12):

from: basic_functions.c

 

PHPAPI int _php_error_log_ex(int opt_err, char *message, int message_len, char *opt, char *headers TSRMLS_DC) /* {{{ */
{
	php_stream *stream = NULL;

	switch (opt_err)
	{
		case 1:		/*send an email */
			if (!php_mail(opt, PHP error_log message, message, headers, NULL TSRMLS_CC)) {
				return FAILURE;
			}
			break;

		case 2:		/*send to an address */
			php_error_docref(NULL TSRMLS_CC, E_WARNING, TCP/IP option not available!);
			return FAILURE;
			break;

		case 3:		/*save to a file */
			stream = php_stream_open_wrapper(opt, a, IGNORE_URL_WIN | REPORT_ERRORS, NULL);
			if (!stream) {
				return FAILURE;
			}
			php_stream_write(stream, message, message_len);
			php_stream_close(stream);
			break;

		case 4: /* send to SAPI */
			if (sapi_module.log_message) {
				sapi_module.log_message(message TSRMLS_CC);
			} else {
				return FAILURE;
			}
			break;

		default:
			php_log_err(message TSRMLS_CC);
			break;
	}
	return SUCCESS;
}
/* }}} */

from: streams.c

 

 

/* Writes a buffer directly to a stream, using multiple of the chunk size */
static size_t _php_stream_write_buffer(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
{
	size_t didwrite = 0, towrite, justwrote;

 	/* if we have a seekable stream we need to ensure that data is written at the
 	 * current stream->position. This means invalidating the read buffer and then
	 * performing a low-level seek */
	if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0 && stream->readpos != stream->writepos) {
		stream->readpos = stream->writepos = 0;

		stream->ops->seek(stream, stream->position, SEEK_SET, &stream->position TSRMLS_CC);
	}


	while (count > 0) {
		towrite = count;
		if (towrite > stream->chunk_size)
			towrite = stream->chunk_size;

		justwrote = stream->ops->write(stream, buf, towrite TSRMLS_CC);

		/* convert justwrote to an integer, since normally it is unsigned */
		if ((int)justwrote > 0) {
			buf += justwrote;
			count -= justwrote;
			didwrite += justwrote;

			/* Only screw with the buffer if we can seek, otherwise we lose data
			 * buffered from fifos and sockets */
			if (stream->ops->seek && (stream->flags & PHP_STREAM_FLAG_NO_SEEK) == 0) {
				stream->position += justwrote;
			}
		} else {
			break;
		}
	}
	return didwrite;

}

通过看源码文件,error_log只是以O_APPEND模式打开文件,然后就是write buf,好吧,没有看到文件锁的影子。而问题也很明显,write可能会调用多次,那么也就基本认定msg并不保证被原子输出,多次的write使得这个问题更严重。

 

多次write不能保证原子操作,那么单次呢?

1.from:man write

 If the file was open(2)ed with <strong>O_APPEND</strong>, the file
       offset is first set to the end of the file before writing.  The
       adjustment of the file offset and the write operation are performed
       as an atomic step.

 

2.from:man write

Atomic/non-atomic: A write is atomic if the whole amount written in one operation is not interleaved with data from any other process. This is useful when there are multiple writers sending data to a single reader. Applications need to know how large a write request can be expected to be performed atomically. This maximum is called {PIPE_BUF}. This volume of IEEE Std 1003.1-2001 does not say whether write requests for more than {PIPE_BUF} bytes are atomic, but requires that writes of {PIPE_BUF} or fewer bytes shall be atomic.

 

man说的大概意思就是如果是O_APPEND模式,文件尾的定位与write调用是原子操作,不会存在write时文件尾还需要再调整,导致错位。当前这个原子性,只保证open和之后的第一次write,后续的write就不保证了。像error_log那样如果buf过长导致了多次write肯定就不保证buf一次完整输出。

继续深究,那么单一次write是原子的吗?man也给出了答案,不是的,只有要写出的数据小于等于PIPE_BUF时才保证原子操作。

问题得到了理论上的解答,下面开始实验验证:

test_error_log.php

 

<!--?php

$str = ;
for($i = 0; $i < (int)$argv[2]; $i++)
{
    $str = $str.$argv[1];
}

for($i = 0; $i < (int)$argv[3]; $i++)
{
    error_log($str.
, 3, ./append.txt);
}

?-->
check_line.py

 

 

filename = ./append.txt

for line in open(filename):
    print len(line)
test.sh

 

 

#!/bin/bash 

rm -f append.txt

for ((counter=0; counter < 10; ++counter))
do
    php test_error_log.php $counter $1 $2 &
done

sleep 2

#python check_line.py > a.txt

python check_line.py | sort | uniq -c

\

验证思路:在输出msg最后加换行符,如果输出的每行与初始buf大小相同,说明本次error_log完整输出,经验证,内核3.5.0-23上PIPE_BUF是8K,8K以内的error_log输出都可以保证完整,否则会存在错乱的风险

 

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1050842.htmlTechArticle探讨php中error_log函数输出内容的原子性问题 前几天跟同事讨论如何在一次login php调用中保证error_log输出的日志都有唯一的标识头,结论是玩...
陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
簡單地說明PHP會話的概念。簡單地說明PHP會話的概念。Apr 26, 2025 am 12:09 AM

phpsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIdStoredInAcookie.here'showtomanageThemeffectionaly:1)startAsessionWithSessionWwithSession_start()和stordoredAtain $ _session.2)

您如何循環中存儲在PHP會話中的所有值?您如何循環中存儲在PHP會話中的所有值?Apr 26, 2025 am 12:06 AM

在PHP中,遍歷會話數據可以通過以下步驟實現:1.使用session_start()啟動會話。 2.通過foreach循環遍歷$_SESSION數組中的所有鍵值對。 3.處理複雜數據結構時,使用is_array()或is_object()函數,並用print_r()輸出詳細信息。 4.優化遍歷時,可採用分頁處理,避免一次性處理大量數據。這將幫助你在實際項目中更有效地管理和使用PHP會話數據。

說明如何使用會話進行用戶身份驗證。說明如何使用會話進行用戶身份驗證。Apr 26, 2025 am 12:04 AM

會話通過服務器端的狀態管理機制實現用戶認證。 1)會話創建並生成唯一ID,2)ID通過cookies傳遞,3)服務器存儲並通過ID訪問會話數據,4)實現用戶認證和狀態管理,提升應用安全性和用戶體驗。

舉一個如何在PHP會話中存儲用戶名的示例。舉一個如何在PHP會話中存儲用戶名的示例。Apr 26, 2025 am 12:03 AM

Tostoreauser'snameinaPHPsession,startthesessionwithsession_start(),thenassignthenameto$_SESSION['username'].1)Usesession_start()toinitializethesession.2)Assigntheuser'snameto$_SESSION['username'].Thisallowsyoutoaccessthenameacrossmultiplepages,enhanc

哪些常見問題會導致PHP會話失敗?哪些常見問題會導致PHP會話失敗?Apr 25, 2025 am 12:16 AM

PHPSession失效的原因包括配置錯誤、Cookie問題和Session過期。 1.配置錯誤:檢查並設置正確的session.save_path。 2.Cookie問題:確保Cookie設置正確。 3.Session過期:調整session.gc_maxlifetime值以延長會話時間。

您如何在PHP中調試與會話相關的問題?您如何在PHP中調試與會話相關的問題?Apr 25, 2025 am 12:12 AM

在PHP中調試會話問題的方法包括:1.檢查會話是否正確啟動;2.驗證會話ID的傳遞;3.檢查會話數據的存儲和讀取;4.查看服務器配置。通過輸出會話ID和數據、查看會話文件內容等方法,可以有效診斷和解決會話相關的問題。

如果session_start()被多次調用會發生什麼?如果session_start()被多次調用會發生什麼?Apr 25, 2025 am 12:06 AM

多次調用session_start()會導致警告信息和可能的數據覆蓋。 1)PHP會發出警告,提示session已啟動。 2)可能導致session數據意外覆蓋。 3)使用session_status()檢查session狀態,避免重複調用。

您如何在PHP中配置會話壽命?您如何在PHP中配置會話壽命?Apr 25, 2025 am 12:05 AM

在PHP中配置會話生命週期可以通過設置session.gc_maxlifetime和session.cookie_lifetime來實現。 1)session.gc_maxlifetime控制服務器端會話數據的存活時間,2)session.cookie_lifetime控制客戶端cookie的生命週期,設置為0時cookie在瀏覽器關閉時過期。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器