Thread: using fork() for multitasking

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    23

    using fork() for multitasking

    Hi,

    I'm currently trying to use fork() to allow my program to run two seperate functions at the same time. however, i am unable to make this work . .

    This is a segment of my code at present.

    --------------------------------

    fork();
    //make child process run lineRead()
    lineRead(fptr2, fptr1);

    mainProcess(); //make parent process run program

    fclose(fptr1);
    fclose(fptr2);

    --------------------------------

    i know this is not correct, i have to add some sort of if statement to ensure a child is present etc. However, i do not know how to do this, as i'm am very new to C ( only 2 days) but quite well versed in java.

    Any help would be appreciated!

    Kind regards,


    Matt

  2. #2
    SleepWalker tjohnsson's Avatar
    Join Date
    Apr 2004
    Posts
    70
    fork() returns child process pid to main process and 0 to child process. -1 if process creation fails.
    create if () {} else {} to find out is currently running process child or main process.

    see: http://www.linuxselfhelp.com/gnu/gli...26.html#SEC562 for more information.

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You're better off leaving fork() alone for a while if all you've got is 2 days experience with C
    I hope you weren't expecting to share memory between these two processes, because fork() doesn't do that.

    Code:
    pid_t pid = fork();
    if ( pid == 0 ) {
      // stuff for child only
      // this normally exits the process when its done
    } else if ( pid != -1 ) {
      // stuff in parent, if child runs
    } else {
      // stuff in parent, with no child
    }
    // stuff "common" again
    // except its not really common, both processes do the same work
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Fork(), pause(), and storing PID's in a linked list
    By vital101 in forum C Programming
    Replies: 10
    Last Post: 09-28-2007, 02:16 AM
  2. Fork() not working.
    By BENCHMARKMAN in forum C++ Programming
    Replies: 3
    Last Post: 08-01-2007, 12:28 AM
  3. Fork - unpredictable?
    By fredkwok in forum Linux Programming
    Replies: 4
    Last Post: 03-26-2006, 02:49 PM
  4. fork(), exit() - few questions!
    By s3t3c in forum C Programming
    Replies: 10
    Last Post: 11-30-2004, 06:58 AM
  5. Daemon programming: allocated memory vs. fork()
    By twisgabak in forum Linux Programming
    Replies: 2
    Last Post: 09-25-2003, 02:53 PM