#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/ipc.h>
#include<sys/msg.h>
#include<sys/types.h>
struct mbuffer{
long mtype;
int mtext;
}stResult;
int main(){
int iPID;
stResult.mtext=0;
stResult.mtype=6;
iPID=fork();
if(iPID<0){
printf("Error....!\n");
exit(1);
}
//... declarations for msgget()
int msgflg,msgid,msgsize;
msgflg = IPC_CREAT|0777;
msgsize=0;
key_t key;
key=70;
//... msgget();
msgid=msgget(key,msgflg);
if(iPID>0){
stResult.mtext += 10;
//msgsnd();
msgsnd(msgid,&stResult,sizeof(stResult),msgflg);
}
else if(iPID==0){
//msgrcv();
while(1){
msgsize=msgrcv(msgid,&stResult,sizeof(stResult),stResult.mtype,msgflg);
if(msgsize>0){
stResult.mtext += 20;
break;
}
}
}
//I want to combine/kill these processes here
//and show this: "Result:30"
wait();
printf("Result:%d\n",stResult.mtext);
//Here I see two results like:"Result=10","Result=30"
return 0;
}
I’m using fork() to have two processes and I’m using msgget(); to communicate them. The thing I want is have an integer. Increase it in one of processes then increase in second one and show total result. In the end I total result + first result after first increase. I used join() or something like that in my school years but I just can’t remember it.
To kill the process you unsurprisingly need to use
kill()(if you really want to kill it). And then yes, usewaitorwaitpid. And remember toexit()after/instead of breaking out of the loop.