最近在使用自编工具处理 unix 系统任务时,遇到了两个意料之外的情况,并非程序错误,而是行为超出了预期。
for (imagefilename in images) { results = process(imagefilename); printf(results); }
图像处理相互独立,因此我尝试使用 fork() 将处理任务分配到多个 CPU 内核以提高速度:
for (child in children) { pipe = create_pipe(); worker(pipe); } // 父进程 for (imagefilename in images) { write(pipe[i_image % N_children], imagefilename); } worker() { while (1) { imagefilename = read(pipe); results = process(imagefilename); printf(results); } }
我创建管道进行进程间通信 (IPC),将文件名发送给子进程 worker。每个 worker 直接写入共享的 STDOUT,导致输出混乱。 flockfile() 函数无法解决问题,因为它受写时复制机制的影响,每个子进程都拥有锁的副本。
我最终选择使用线程而非 fork() 来解决此问题,避免了复杂的管道操作。 代码如下:
for (children) { pthread_create(worker, child_index); } for (children) { pthread_join(child); } worker(child_index) { for (i_image = child_index; i_image < ... ) { // ... } }
这种方法更简洁有效。看来,某些情况下线程比进程更适用。
第二个程序可能需要文件名而非文件描述符作为命令行参数,因为它可能自行调用 open()。传递文件名会导致重新打开文件并从头开始读取,这无法满足需求。
我尝试使用 /dev/fd/N 传递文件描述符,但它在 Linux 系统上表现得像符号链接,与传递文件名效果相同。
解决方法是使用管道而非文件。/dev/fd/N 在管道上能正确传递文件描述符。 这可以通过将 open("filename") 替换为 popen("cat filename") 来实现,但这并非理想解决方案。 这在 BSD 系统上的表现可能有所不同。
以上就是UNIX 下奇怪的事情的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号