一个进程负责发送文件,一个进程负责接受文件。 //实现文件的拷贝,本进程负责发送数据到消息队列,文件名由命令行参数传递 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define MSGTYPE 100 #define DATASIZE 512 struct msgbuf { long mtype; char mtext[1]; }; //封装每次要传送的消息 struct databuf { size_t size;//数据大小 char data[DATASIZE];//数据 }; int main(int argc, char *argv[]) { //如果参数个数不是2,说明参数错误 if( 2!=argc ) { printf("参数错误!/n"); return -1; } char* msgpath="msgqueue"; int fd; if( access(msgpath, F_OK)!=0 ) { fd=open(msgpath, O_RDWR|O_CREAT, 0666); close(fd); } //创建key key_t key=ftok(msgpath, 'a'); if( -1==key ) { perror("ftok"); exit(1); } //获取msgid int msgid=msgget(key, IPC_CREAT|0666); if( -1==msgid ) { perror("msgget"); exit(1); } int msgsize=sizeof(struct msgbuf)+sizeof(struct databuf)-sizeof(long); struct msgbuf* sndmsg=(struct msgbuf*)malloc(msgsize+sizeof(long)); memset(sndmsg, 0, msgsize+sizeof(long)); sndmsg->mtype=MSGTYPE; fd=open(argv[1], O_RDONLY); if( fd<0 ) { perror("open file "); exit(1); } struct databuf db; //从文件中读取数据并发送到消息队列中,采用阻塞模式 while( (db.size=read(fd, db.data, DATASIZE ))!=0 ) { memcpy(sndmsg->mtext, &db, sizeof(struct databuf)); if( -1==msgsnd(msgid, sndmsg, msgsize, 0) ) { perror("msgsnd"); exit(1); } } close(fd); free(sndmsg); exit(0); } //实现文件的拷贝,本进程负责从消息队列中读取数据,文件名由命令行参数传递 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #define MSGTYPE 100 #define DATASIZE 512 struct msgbuf { long mtype; char mtext[1]; }; struct databuf { size_t size; char data[DATASIZE]; }; int main(int argc, char *argv[]) { if( 2!=argc ) { printf("参数错误!/n"); return -1; } char* msgpath="msgqueue"; key_t key=ftok(msgpath, 'a'); if( -1==key ) { perror("ftok"); exit(1); } int msgid=msgget(key, IPC_CREAT|0666); if( -1==msgid ) { perror("msgget"); exit(1); } int msgsize=sizeof(struct msgbuf)+sizeof(struct databuf)-sizeof(long); struct msgbuf* getmsg=(struct msgbuf*)malloc(msgsize+sizeof(long)); memset(getmsg, 0, msgsize+sizeof(long)); getmsg->mtype=MSGTYPE; int fd=open(argv[1], O_WRONLY|O_CREAT, 0666); if( fd<0 ) { perror("open file "); exit(1); } struct databuf db; struct msqid_ds buf; while(1) { msgctl(msgid, IPC_STAT, &buf); if( 0==buf.msg_qnum ) { if( -1==msgctl(msgid, IPC_RMID, &buf) ) { perror("delete msgqueue"); exit(1); } break; } if( -1==msgrcv(msgid, getmsg, msgsize, MSGTYPE, 0) ) { perror("msgsrc"); exit(1); } memcpy(&db, getmsg->mtext, sizeof(struct databuf)); if(write(fd, db.data, db.size)!=db.size) { perror("write file"); exit(1); } } close(fd); free(getmsg); exit(0); }