Evren Ozturk
Evren Ozturk

Reputation: 928

How to combine/kill a fork()

#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.

Upvotes: 0

Views: 379

Answers (3)

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143081

To kill the process you unsurprisingly need to use kill() (if you really want to kill it). And then yes, use wait or waitpid. And remember to exit() after/instead of breaking out of the loop.

Upvotes: 2

Karoly Horvath
Karoly Horvath

Reputation: 96258

Now both processes show the result.

The main process will wait till it receives the message, so simply exit after msgsnd.

Upvotes: 1

mah
mah

Reputation: 39807

I suspect you don't mean to use fork() and instead you mean to use pthread_create() -- in which case you would use pthread_join().

Upvotes: 0

Related Questions