# 进程间通信(IPC)是操作系统中的一个重要概念,Linux 提供了多种进程间通信的方式。下面是一个使用管道(pipe)进行进程间通信的 Python 示例代码。
import os
def main():
# 创建一个管道
r, w = os.pipe()
# 创建子进程
pid = os.fork()
if pid > 0:
# 父进程
os.close(r) # 关闭读端
print("Parent process is writing")
write_pipe = os.fdopen(w, 'w')
write_pipe.write("Hello from parent process!")
write_pipe.close()
else:
# 子进程
os.close(w) # 关闭写端
print("Child process is reading")
read_pipe = os.fdopen(r)
message = read_pipe.read()
print(f"Message from parent: {message}")
read_pipe.close()
if __name__ == "__main__":
main()
os.pipe() 函数创建一个管道,并返回一对文件描述符 (r, w),分别表示读端和写端。os.fork() 创建一个子进程。父进程和子进程通过管道进行通信。这个例子展示了如何使用管道在父进程和子进程之间传递消息。
上一篇:linux 赋权
下一篇:linuxrar解压命令
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站