example2-01.c

来自「Linux网络测试程序」· C语言 代码 · 共 31 行

C
31
字号
//父进程通过管道向子进程传送消息,然后子进程再向屏幕打印出所收到的字符串 

#include	<stdlib.h>
#include	<unistd.h>
#include	<sys/types.h>

int main(void)
{
	int		n,
	 	    fd[2];        // 本例把fd[0]和fd[1]分别当做读入管道和写出管道。
	pid_t	pid;
	char	line[1024];

	if (pipe(fd) < 0)   // error process 
		exit(0);
		
	pid = fork();       // 开一个进程 
	if (pid < 0)        // 错误处理                // 执行fork(),若返回值pid<0,说明fork()执行失败,失败原因在errno中。
		exit(0);
	else if (pid > 0) { /* The code of parent */   // 执行fork(),若返回值pid>0,说明fork()执行成功,得到的值为新建立的子进程代码(pid)。
		close(fd[0]);
		write(fd[1], "I am from parent!\n", 19);
	}
	else {              /* The code of child */    // 执行fork(),若返回值pid==0,说明已经新建子进程
		close(fd[1]);
		n = read(fd[0], line, 1024);
		write(STDOUT_FILENO, line, n);
	}
	exit(0);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?