zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C/C++ 进程通信----管道

C++进程通信 ---- 管道
2023-09-11 14:14:44 时间
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{
        int fd[2];
        char str[256];
        if (pipe(fd) < 0)
        {
                printf("create pipe failed!\n");
                exit(1);
        }

        write(fd[1], "create the pipe successfuilly!\n", 31);
        read(fd[0], str, sizeof(str));
        printf("%s\n", str);
        printf("pipe file descriptors are %d , %d \n", fd[0], fd[1]);
        close(fd[0]);
        close(fd[1]);
        return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <limits.h>


#define BUFSIZE PIPE_BUF 

void err_quit(char* msg)
{
	printf("%s\n", msg);
	exit(1);
}

int main()
{
	int pid;
	int fd[2];
	char buf[BUFSIZE] = "hello my child, i am zhaoyun that is your perent\n";
	int len;

	if (pipe(fd) < 0)
	{
		err_quit("pipe failed\n");
	}

	//create child
	if ((pid = fork() < 0))
	{
		err_quit("fork failed\n");
	}
	else if (pid > 0)
	{
		close(fd[0]);
		write(fd[1], buf, strlen(buf));
		exit(0);
	}
	else
	{
		close(fd[1]);
		len = read(fd[0], buf, BUFSIZE);
		if (len < 0)
		{
			err_quit("process failed when read a pipe\n");
		}
		else
		{
//			printf("%s\n", buf);
			write(STDOUT_FILENO, buf, len);
		}
		exit(0);
	}
	return 0;
}