踩坑简介
本想练习下习题3.1,没想到坑是一个接一个,看代码
代码
myhead.h
#ifndef MYHEAD_H_
#define MYHEAD_H_
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<mqueue.h>
#define MAXLINE 4096
#define FILE_MODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP)
#endif
ctl.c
#include"myhead.h"
#include<sys/msg.h>
#define MSG_R 0400
#define MSG_W 0200
#define SVMSG (MSG_R | MSG_W | MSG_R >> 3 | MSG_W >> 3)
struct msgbuf
{
__syscall_slong_t mtype; /* type of received/sent message */
char mtext[1]; /* text of the message */
};
int main(int argc, char**argv)
{
int msqid;
struct msqid_ds info;
struct msgbuf buf;
memset(&buf, 0, sizeof(buf));
msqid = msgget(IPC_PRIVATE, SVMSG | IPC_CREAT);
buf.mtype = 1;
buf.mtext[0] = 1;
msgsnd(msqid, &buf, 1, 0);
msgctl(msqid, IPC_STAT, &info);
printf("read-write:%03o, cbypes = %lu, qnum = %lu, qbytes = %lu, seq = %u\n",
info.msg_perm.mode & 0777, info.msg_cbytes, info.msg_qnum,info.msg_qbytes, info.msg_perm.__seq);
system("ipcs -q");
//show information on IPC facilities
// Write information about active message queues.
msgctl(msqid, IPC_RMID, NULL);
return 0;
}
踩坑详解
- 一开始直接包含头文件时,编译一直提示
error: storage size of ‘buf’ isn’t known
,查了半天没找到原因,只好查看了<sys/msg.h>
的文本,发现struct msgbuf buf
由宏定义所包括,而经过测试本系统未定义这个宏,导致一直没编入程序。 - 书中定义结构体,与实际系统中有一定的差异。查看
man msgctl
可得实际结构体如下:
struct msqid_ds {
struct ipc_perm msg_perm; /* Ownership and permissions */
time_t msg_stime; /* Time of last msgsnd(2) */
time_t msg_rtime; /* Time of last msgrcv(2) */
time_t msg_ctime; /* Time of last change */
unsigned long __msg_cbytes; /* Current number of bytes in
queue (nonstandard) */
msgqnum_t msg_qnum; /* Current number of messages
in queue */
msglen_t msg_qbytes; /* Maximum number of bytes
allowed in queue */
pid_t msg_lspid; /* PID of last msgsnd(2) */
pid_t msg_lrpid; /* PID of last msgrcv(2) */
};
struct ipc_perm {
key_t __key; /* Key supplied to msgget(2) */
uid_t uid; /* Effective UID of owner */
gid_t gid; /* Effective GID of owner */
uid_t cuid; /* Effective UID of creator */
gid_t cgid; /* Effective GID of creator */
unsigned short mode; /* Permissions */
unsigned short __seq; /* Sequence number */
};