zoukankan      html  css  js  c++  java
  • 管道

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    int main()
    {
    	int r, p1, p2, fd[2];
    	char buf[50], s[50];
    	pipe(fd);	// 创建管道
    	while((p1 = fork()) == -1);
    	if(p1 == 0)
    	{
    		lockf(fd[1], 1, 0);
    		sprintf(buf, "child process p1 is sending message!
    ");
    		printf("child process p1!
    ");
    		write(fd[1], buf, 50);	// 把buf中的字符写入管道
    		sleep(5);
    		lockf(fd[1], 0, 0);
    		exit(0);
    	}
    	else
    	{
    		while((p2 = fork()) == -1);
    		if(p2 == 0)
    		{
    			lockf(fd[1], 1, 0);
    			sprintf(buf, "child process p2 is sending message!
    ");
    			printf("child process p2!
    ");
    			write(fd[1], buf, 50);	// 把buf中的字符写入管道
    			sleep(5);
    			lockf(fd[1], 0, 0);
    			exit(0);
    		}
    		wait(0);
    		if((r = read(fd[0], s, 50) == -1))
    		{
    			printf("can't read pipe
    ");
    		}
    		else
    		{
    			printf("%s
    ", s);
    		}
    		wait(0);
    		if((r = read(fd[0], s, 50) == -1))
    		{
    			printf("can't read pipe
    ");
    		}
    		else
    		{
    			printf("%s
    ", s);
    		}
    		exit(0);
    	}
    	return 0;
    }
    

      利用系统调用lockf(fd,mode,size),对指定文件的指定区域(由size指示)进行加锁或解锁,以实现进程同步或互斥。其中,fd是文字描述字;mode是锁定方式,=1表示加锁,=0表示解锁;size是指定文件的指定区域,用0表示从当前位置到文件尾

    #include <sys/wait.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdio.h>
    int main()
    {
    	int x, fd[2];
    	char buf[30], s[30];
    	pipe(fd);
    	while((x = fork()) == -1);
    	if(x == 0)
    	{
    		sprintf(buf, "this is an example
    ");
    		write(fd[1], buf, 30);
    		exit(0);
    	}
    	else
    	{
    		wait(0);
    		read(fd[0], s, 30);
    		printf("%s", s);
    	}
    	return 0;	
    }
    

      

  • 相关阅读:
    oracle 删除表中重复数据留一条
    C# 特性
    oracle 常用简单命令语句
    2017年学习计划
    java web开发基础学习
    Java Axis2支持json
    java基础教程
    axis2 发布webservice
    孤荷凌寒自学python第103天认识区块链017
    孤荷凌寒自学python第102天认识区块链016
  • 原文地址:https://www.cnblogs.com/mjn1/p/10753020.html
Copyright © 2011-2022 走看看