Search code examples
cprocessforkexecvp

How to use child process in c


I have a problem figuring out how to use active child processes after they are created in the fork(). I see from another terminal that they are still active until I execute the exit success. If I wanted to say for example: I want to make the child process with pid 10243, active at the moment, do this method. I would like to call the method after all the children have been initialized, so after the fork. Do I have to type execvp ()? execvp (methodName (a))?

EDIT: I will try to add a similar code in order to be more specific

So let's say that I did a cycle where I create n child

            
        switch (pid = fork()) {     
            case -1:
                /* Handle error */
                fprintf(stderr, "%s, %d: Errore (%d) nella fork\n",
                __FILE__, __LINE__, errno);
                exit(EXIT_FAILURE);
            case 0: 

                    //here I have saved the pid of the child process        
                
            break;
            
        
            default:

            /* PARENT CODE: nothing here */
            wait(NULL);     
            exit(0);            

            break;
        }
    }```

So at that point I have created n number of child process. Now I want, for example, that the child with the pid 10342 do a method called "method1()", and the child with the pid 10343 do a method called "method2()".

How can I say that? Is that possibile? Because I need first to create all the child and then use them while the "main process" is in stand by with an infinte cycle. Like: 

```int u = 0;
    while(u == 0){         I will handle the end of this with a signal 
        
        }
    }
exit(EXIT_SUCCESS);

Solution

  • From the man page of fork:

    The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same content.

    That means, all functions in the memory can be called by the parent and the child processes, but there is no way, that one process can call a function which resides in the memory space of another process.

    For that you need IPC (Inter Process Communication).

    Addendum:

    After fork, you're able to run every function you like (in the child process - i hope you know what that means, if not, the provided link will help you out). But to 'make' a child process active and run a certain method is only possible via IPC.