php无法生成类似.pid的标识进程的临时文件

本文探讨了在PHP与C语言中,文件句柄对unlink操作的影响差异。通过示例代码展示了当文件被打开并保持句柄时,两种语言下unlink的行为不同:C语言中文件不会立即删除,而PHP则会报权限错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在linux C编程里,大家都知道在一个进程里建立一个文件,保持打开状态,然后unlink掉文件,它并不实际删除,而是等到进程结束时,所有的fd都关闭了,才真正清除掉。
在php里,用同样的操作方法想得到一个标识一个进程尚在运行的pid文件,未果!
在php里,如果创建一个文件,并保留此文件的引用指针,则无法unlink文件,会报错:Warning: unlink Permissdenied。如果不保留文件指针或将其unset掉,则文件立即删除了,而不是等到进程结束。也就是,同C编程相比,php不允许删除尚有引用指针的文件。
下面是php和C的代码:
php:

<?php
$filename = "/tmp/test_php.pid";
$fp = fopen($filename, 'w');
//unset($fp);
unlink($filename);
sleep(6);

C:

#include <stdio.h>

int main()
{
char *filename = "/tmp/test_c.pid";
FILE *fp;
fp = fopen(filename, "w");
unlink(filename);
sleep(6);
}

[19-Jul-2025 02:06:28] NOTICE: using inherited socket fd=7, "/tmp/php-cgi-74.sock" [19-Jul-2025 02:06:28] NOTICE: using inherited socket fd=7, "/tmp/php-cgi-74.sock" [19-Jul-2025 02:06:28] NOTICE: fpm is running, pid 9880 [19-Jul-2025 02:06:28] NOTICE: ready to handle connections [19-Jul-2025 04:30:01] NOTICE: Reloading in progress ... [19-Jul-2025 04:30:01] NOTICE: reloading: execvp("/www/server/php/74/sbin/php-fpm", {"/www/server/php/74/sbin/php-fpm", "--daemonize", "--fpm-config", "/www/server/php/74/etc/php-fpm.conf", "--pid", "/www/server/php/74/var/run/php-fpm.pid"}) [19-Jul-2025 04:30:01] NOTICE: using inherited socket fd=7, "/tmp/php-cgi-74.sock" [19-Jul-2025 04:30:01] NOTICE: using inherited socket fd=7, "/tmp/php-cgi-74.sock" [19-Jul-2025 04:30:01] NOTICE: fpm is running, pid 16670 [19-Jul-2025 04:30:01] NOTICE: ready to handle connections [20-Jul-2025 04:30:01] NOTICE: Reloading in progress ... [20-Jul-2025 04:30:01] NOTICE: reloading: execvp("/www/server/php/74/sbin/php-fpm", {"/www/server/php/74/sbin/php-fpm", "--daemonize", "--fpm-config", "/www/server/php/74/etc/php-fpm.conf", "--pid", "/www/server/php/74/var/run/php-fpm.pid"}) [20-Jul-2025 04:30:01] NOTICE: using inherited socket fd=7, "/tmp/php-cgi-74.sock" [20-Jul-2025 04:30:01] NOTICE: using inherited socket fd=7, "/tmp/php-cgi-74.sock" [20-Jul-2025 04:30:01] NOTICE: fpm is running, pid 81380 [20-Jul-2025 04:30:01] NOTICE: ready to handle connections 是什么意思
07-22
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值