dポイントプレゼントキャンペーン実施中!

msend.c,mrecv.cを参考にして)10秒ごとにメッセージで
「10秒経過」を送信するプログラムを作成せよ。mrecv.cで受信を確認する。
msend.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>

int main() {
struct msgbuf {
long mtype;
char mtext[256];
};
char line[256];
int msgid;
key_t msgkey;
struct msgbuf msgdata, *p;

p=&msgdata;
printf("Enter message: ");
fflush(stdout);
fgets(line,sizeof(line),stdin);
if (sscanf(line,"%[^\n]",p->mtext)>0) {
p->mtype=getpid();
msgkey=ftok("mrecv",'a');
msgid=msgget(msgkey,IPC_CREAT|0666);
msgsnd(msgid,p,sizeof(p->mtext),0);
}
return EXIT_SUCCESS;
}


mrecv.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>


int main() {
struct msgbuf {
long mtype;
char mtext[256];
};
int msgid;
key_t msgkey;
struct msgbuf msgdata, *p;

p=&msgdata;
msgkey=ftok("mrecv",'a');
msgid=msgget(msgkey,IPC_CREAT|0666);
while (1) {
msgrcv(msgid,p,sizeof(p->mtext),0,0);
printf("message received from %ld\n%s\n",p->mtype,p->mtext);
}
return EXIT_SUCCESS;
}

以下のプログラムに4行追加するんですが(2)(3)(4)がわかりません。教えてください
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
int main() {
struct msgbuf {
long mtype;
char mtext[256];
};
char line[256] = "10 seconds has passed!!";
int msgid;
key_t msgkey;
struct msgbuf msgdata, *p;
ここに4行追加して下さい。
(1)鍵を作る(mrecv.cと同じファイル名から作る)。
msgid=msgget(msgkey,IPC_CREAT|0666);
(2)msggetシステムコールを行い、msgidを得る。
(3)msgdataのアドレスをポインタ変数pに入れる。
(4)msgdataのメンバmtypeにプロセスidを入れる。
while (1) {
sleep(10);
sscanf(line,"%[^\n]",p->mtext);
msgsnd(msgid,p,sizeof(p->mtext),0);
}
return EXIT_SUCCESS;
}

A 回答 (1件)

以下のようにしてください。


---------------------------------------
//ここに4行追加して下さい。
//(1)鍵を作る(mrecv.cと同じファイル名から作る)。
msgkey=ftok("mrecv",'a');
//(2)msggetシステムコールを行い、msgidを得る。
msgid=msgget(msgkey,IPC_CREAT|0666);
//(3)msgdataのアドレスをポインタ変数pに入れる。
p = &msgdata;
//(4)msgdataのメンバmtypeにプロセスidを入れる。
p->mtype=getpid();
---------------------------------------
以下、mrecvの実行結果です。
message received from 7077
10 seconds has passed!!
message received from 7077
10 seconds has passed!!
message received from 7077
10 seconds has passed!!
message received from 7077
10 seconds has passed!!

実行環境は以下の通りです
CentOS release 6.3 (Final)
gcc version 4.4.6 20120305 (Red Hat 4.4.6-4) (GCC)
    • good
    • 1
この回答へのお礼

ありがとうございました

お礼日時:2015/06/11 00:49

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!