0

I have a string (fileContents) in shared memory that consists of a 9 lines:

sprintf(shared_memory, fileContents.c_str());

I want to call on fork() to create the same number of processes as lines. These processes will manipulate each line. However, I have no idea where to start when calling fork(). Every example I have looked at just consists of returning the process ID of parents and child processes and not showing how or when the processes executes something.

Any guidance would be appreciated, thanks!

2
  • Do you want the processes to continue running the same program after forking, or to launch a different program? In the former case, just keep going after forking and run the rest of your program, in the latter case you want to call exec to run a new executable in the child process Commented Mar 7, 2013 at 18:56
  • @JonathanWakely I'm not sure I completely understand your question, but after each line is manipulated I am just going to print out the shared memory and the program will end. Commented Mar 7, 2013 at 19:21

1 Answer 1

2

Every example I have looked at just consists of returning the process ID of parents and child processes

That's not correct.

The parent process will get the process id of the child process, but the child process will know it's the child process because fork() returns 0.

This code will fork 9 times, with each child doing specific work.

for( int line = 1; line <= 9; ++line ) // *cough*
{
    if ( fork() == 0 )
    {
        // Child process.  Handle line, and exit()
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response it helped quit a bit. Just one more question. I seem to be hung up on the child processes. Are they objects? Can you just explain how they are used. Thanks =).
You don't "use" a process, a process is the operating system entity that is running your program, it's the thing that starts from main() and executes all the code in your program until it exits. The fork() system call creates an (almost) identical copy of the current process, which is running the same line of the same program. Before a call to fork() you have one process running your code, after fork() you have two processes running your code. You need to make sure you understand that before trying to do do anything more with fork(), or you'll get quite confused.
@Nikkisixx2 "what is a process" is a question with a looooong answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.