fork() question

This is a discussion on fork() question within the C Programming forums, part of the General Programming Boards category; why does this: Code: #include <stdio.h> int main() { short int pid, i; for (i=0; i<=1; i++) { pid = ...

  1. #1
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300

    fork() question

    why does this:

    Code:
    #include <stdio.h>
    
    int main() {
            short int pid, i;
            for (i=0; i<=1; i++) {
                    pid = fork();
                    if (pid==0) printf("hello%d\n",i);
                    else printf("pid: %d\n", pid);
                    fflush(NULL);
            }   
    }
    produce this:
    Code:
    hello0
    hello1
    pid: 4790
    pid: 4789
    hello1
    pid: 4791
    esp. this red bit...
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    fork returns a pid_t, not a short int. To print a short int, use %hd. #include <unistd.h> for fork.

    >fflush(NULL);

    *sad face*

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,821
    The first child process doesn't exit, so it too runs a loop with i = 1
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A small question about fork( )
    By mlhazan in forum C Programming
    Replies: 4
    Last Post: 08-13-2008, 09:18 PM
  2. fork() question
    By cstudent in forum C Programming
    Replies: 3
    Last Post: 04-25-2008, 07:48 AM
  3. Question sorting character arrays: C programming
    By NeoSigma in forum C Programming
    Replies: 3
    Last Post: 05-23-2003, 10:28 PM
  4. Fork() child process question
    By CrackDown in forum Linux Programming
    Replies: 0
    Last Post: 04-17-2003, 12:58 PM
  5. opengl DC question
    By SAMSAM in forum Game Programming
    Replies: 6
    Last Post: 02-26-2003, 09:22 PM

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21