linue 通信

create_shm.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/shm.h> 
int main()
{  int shm_id;
   shm_id = shmget(IPC_PRIVATE, 4096, 0666); // 6=110b(rw-) 
   if (shm_id < 0)
	{
    	perror("shmget id < 0 ");
	exit(0); 
  	}

printf("Shared memory area successfully created:%d\n", shm_id);
system("ipcs -m");
 }

write_shm.c

#include <stdio.h>
#include <sys/shm.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{  int  shm_id; 
char  *shm_buf;
shm_id = atoi(argv[1]);  
shm_buf=shmat(shm_id, 0, 0);  

printf("write data to shared memory :\n");
sprintf (shm_buf, "write 123456abc into shared memory");
printf("%s \n", shm_buf); 
}

read_shm.c

#include <stdio.h>
#include <sys/shm.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
	int shm_id;
	char *shm_buf, str[50];
	shm_id = atoi(argv[1]);
	shm_buf=shmat(shm_id, 0, 0);
	printf("Read something from shared memory:\n");
	sprintf(str, shm_buf);
	printf("%s\n", str);
	system("ipcs -m");
}

pipe.c

/*pipe.c*/
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int pid1,pid2;
 
main( )
    { 
int fd[2];
char outpipe[100],inpipe[100];
pipe(fd);                       /*creat a pipe*/
while ((pid1=fork( )) == -1) ;
if(pid1==0)
  {
    lockf(fd[1],1,0);   //lock
    sprintf(outpipe,"child 1 process is sending message!"); 
    /*put the string into outpipe*/
    write(fd[1],outpipe,50);     /*write 50 bytes to outpipe*/
    sleep(5);                 /*sleep 5 seconds*/
    lockf(fd[1],0,0);   //unlock
    exit(0);
            }
else
           {
	while((pid2=fork( ))==-1);
    	if(pid2==0)
	{    	lockf(fd[1],1,0);           /*mutual*/
   		sprintf(outpipe,"child 2 process is sending message!");
                		write(fd[1],outpipe,50);
                		sleep(5);
           		lockf(fd[1],0,0);  //unlock
                 		exit(0);
            	}
               else
                {  wait(0);              /*synchronization*/
         	 read(fd[0],outpipe,50);   /*read 50 bytes from inpipe*/
                	printf("%s\n",outpipe);
         	wait(0);
         	read(fd[0],outpipe,50);
         	printf("%s\n",outpipe);
                exit(0);
               }
        }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值