进程间通信

#include <stdio.h>
#include <stdlib.h>


#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <fcntl.h>


struct msgbuf
{
    long typeid;


    char msg[1024];
};


int main(int argc, char *argv[])
{
     pid_t pid;
     
     int fd[2];


     key_t key = ftok("/tmp/4",0);


     int msgid = msgget(key,IPC_CREAT | IPC_NOWAIT);


     if(msgid < 0)
     {
         perror("msg creat error!");
exit(1);
     }


     //int shmid = shmget(IPC_PRIVATE,1024,0);
     
     #if 0
     if(pipe(fd) < 0)
     {
         perror("pipe error!");
exit(1);
     }
     #endif


     pid = fork();
     
     if(pid < 0)
     {
         perror("fork error!");
exit(1);
     }
     
     if(pid == 0)
     {
         char src[100] = "hello world";
         
         struct msgbuf msg = {1,"hello world"};
         struct msgbuf msg2 = {2,"hello world2"};
         struct msgbuf msg3 = {3,"hello world3"};
         struct msgbuf msg4 = {4,"hello world4"};
         struct msgbuf msg5 = {5,"hello world5"};


         msgsnd(msgid,&msg,sizeof(msg),IPC_NOWAIT); 
         msgsnd(msgid,&msg2,sizeof(msg2),IPC_NOWAIT); 
         msgsnd(msgid,&msg3,sizeof(msg3),IPC_NOWAIT); 
         msgsnd(msgid,&msg4,sizeof(msg4),IPC_NOWAIT); 
         msgsnd(msgid,&msg5,sizeof(msg5),IPC_NOWAIT); 


//共享内存
#if 0
         char *caddr = shmat(shmid,NULL,0);




strcpy(caddr,src);
         #endif
         //无名管道
#if 0
close(fd[0]);


write(fd[1],src,strlen(src));
write(fd[1],src,strlen(src) - 2);
write(fd[1],src,strlen(src) - 3);
write(fd[1],src,strlen(src) - 4);
         #endif
         
//普通文件
#if 0
int fd;


fd = open("a.txt",O_WRONLY);


write(fd,src,strlen(src));


close(fd);
#endif
     }
     else
     {
         sleep(1);
 
         char src[100];


struct msgbuf msg;
         
         msgrcv(msgid,&msg,sizeof(msg),4,IPC_NOWAIT);


printf("recv:%s\n",msg.msg);




//共享内存
#if 0
char *paddr = shmat(shmid,NULL,0);


strcpy(src,paddr);
         #endif
         //无名管道
#if 0
close(fd[1]);


read(fd[0],src,sizeof(src));
         #endif
         //普通文件
#if 0
int fd;


fd = open("a.txt",O_RDONLY);
         
read(fd,src,sizeof(src));




close(fd);
         #endif


// printf("src = %s\n",src);
         
wait(NULL);
     }
     
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值