⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄

📁 包含几个用不同方式(共享内存、socket、FIFO、消息队列等)实现进程通信的小程序
💻
字号:
//父进程通过管道向子进程传送消息,然后子进程再向屏幕打印出所收到的字符串     
   
#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);   
}   

//父进程通过管道向子进程传送消息,然后子进程再向屏幕打印出所收到的字符串  
 
#include	 
#include	 
#include	 
 
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -