当前位置: 技术问答>linux和unix
进程通信 ???
来源: 互联网 发布时间:2016-07-13
本文导语: #include #include #include #include #include #include #include #define KEY 12 typedef struct { long type; char *ch; }msgp; int main() { msgp msg; pid_t pid; ...
#include
#include
#include
#include
#include
#include
#include
#define KEY 12
typedef struct {
long type;
char *ch;
}msgp;
int main()
{ msgp msg;
pid_t pid;
int m;
key_t key=1234;
m=msgget(key,IPC_CREAT|0600);
static int k=0;
if(m==-1)
{ printf("getting message goes wrong!n");
printf("please enter any keys to withdraw....n");
getchar();
return 2;
}
while((pid=fork())==-1);
if(pid==0){
msg.ch=(char *)malloc(100);
if(msg.ch==NULL){
printf("memory malloc wrong!n");
exit(0);
}
char buff[100];
int flag;
msg.type=1;
printf("please input a string !n");
gets(buff);
strcpy(msg.ch,buff);
flag=msgsnd(m,(void*)&msg,strlen(msg.ch),0); // 发送消息到消息队列
k=1;
exit(0);
}
else{
sleep(5);// 等待子进程结束
while(k==0);
msgrcv(m,(void*)&msg,strlen(msg.ch),1,0);
printf("parent receive :");
printf("%ld,%sn",msg.type,msg.ch);
msgctl(m,IPC_RMID,NULL);
exit(0);
}
}
该程序能编译过去,但在执行的时候显示 “bad system call” 我 不知道错在那了 ,请各位帮帮忙!
#include
#include
#include
#include
#include
#include
#define KEY 12
typedef struct {
long type;
char *ch;
}msgp;
int main()
{ msgp msg;
pid_t pid;
int m;
key_t key=1234;
m=msgget(key,IPC_CREAT|0600);
static int k=0;
if(m==-1)
{ printf("getting message goes wrong!n");
printf("please enter any keys to withdraw....n");
getchar();
return 2;
}
while((pid=fork())==-1);
if(pid==0){
msg.ch=(char *)malloc(100);
if(msg.ch==NULL){
printf("memory malloc wrong!n");
exit(0);
}
char buff[100];
int flag;
msg.type=1;
printf("please input a string !n");
gets(buff);
strcpy(msg.ch,buff);
flag=msgsnd(m,(void*)&msg,strlen(msg.ch),0); // 发送消息到消息队列
k=1;
exit(0);
}
else{
sleep(5);// 等待子进程结束
while(k==0);
msgrcv(m,(void*)&msg,strlen(msg.ch),1,0);
printf("parent receive :");
printf("%ld,%sn",msg.type,msg.ch);
msgctl(m,IPC_RMID,NULL);
exit(0);
}
}
该程序能编译过去,但在执行的时候显示 “bad system call” 我 不知道错在那了 ,请各位帮帮忙!
|
gdb跟踪一下,或者printf打印一下,看看到哪一步出错的。
感觉是
msgctl(m,IPC_RMID,NULL);
感觉是
msgctl(m,IPC_RMID,NULL);