2024/4/2 IOday4

使用文件IO 实现父进程向子进程发送信息,并总结中间可能出现的各种问题

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#define MAX_SIZE 256

int main(int argc, const char *argv[])
{
	int fd[2];
	pid_t pid;
	char buf[MAX_SIZE];
	//创建管道
	if(pipe(fd)==-1)
	{
		perror("pipe");
	    return -1;
	}
	pid=fork();
	//父进程发送消息到管道,写之前关闭读端
	if(pid>0)
	{
		close(fd[0]);//关闭读端
		strcpy(buf,"hello my son");
		write(fd[1],buf,strlen(buf)+1);//传数据到管道
		close(fd[1]);//关闭写端
		wait(NULL);//等待子进程结束
    }else if(pid==0){//子进程从管道接收消息
		close(fd[1]);//关闭写端
		read(fd[0],buf,MAX_SIZE);
		printf("子进程接收到的%s\n",buf);
		close(fd[0]);//关闭读端
	}else if(pid==-1){
		perror("pid");
		return -2;


	}
	

	return 0;
}

相关推荐

  1. 4/4 清明work

    2024-04-02 23:00:03       35 阅读
  2. <span style='color:red;'>4</span>.<span style='color:red;'>4</span>总结

    4.4总结

    2024-04-02 23:00:03      40 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-02 23:00:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-02 23:00:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-02 23:00:03       82 阅读
  4. Python语言-面向对象

    2024-04-02 23:00:03       91 阅读

热门阅读

  1. 系统学习Docker:1_Docker简介以及2_安装Docker

    2024-04-02 23:00:03       43 阅读
  2. vi/vim编辑器

    2024-04-02 23:00:03       39 阅读
  3. 开源中文大语言模型汇总

    2024-04-02 23:00:03       37 阅读
  4. pip/conda导出或导入环境

    2024-04-02 23:00:03       65 阅读
  5. 迪米特法则

    2024-04-02 23:00:03       37 阅读
  6. 10个大幅提升MySQL效率的使用技巧

    2024-04-02 23:00:03       36 阅读
  7. 计算机笔记(1)

    2024-04-02 23:00:03       29 阅读