Find the answer to your Linux question:
Results 1 to 4 of 4
My sw.c is as follows: -------------------------------------------------------------- #include<stdio.h> int main() { int pid; pid = fork(); switch(pid) { case 0: printf ("Am child, my ID: %d", getpid() ); printf ("Am child, ...
  1. #1
    Just Joined!
    Join Date
    May 2009
    Posts
    7

    fork() & Switch Case in C

    My sw.c is as follows:

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

    #include<stdio.h>

    int main()
    {
    int pid;
    pid = fork();

    switch(pid)
    {
    case 0:
    printf ("Am child, my ID: %d", getpid() );
    printf ("Am child, my Parent id: %d",getppid() );
    break;

    case -1:
    printf ("The child process has not created");
    break;

    default:
    printf ("am in default , process id: %d",
    getpid());

    sleep(10);
    break;
    } // switch case closed

    system("ps");
    } // main function close

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

    Now i think, neither parent should not execute the code inside the default block of the nor the child.

    As we know, value of pid=0; so it should not execute default block! It should only execute the block with case 0. right.

    When i look at the lines of code which i keep in bold & italic, these line return me same ID.

    1) Why? How?

    2) What is the fundamental concept behind a fork()?

    3)What is the role & scope of the Parent process then?

    please help. I will be thankful to you.

  2. #2
    Linux Guru coopstah13's Avatar
    Join Date
    Nov 2007
    Location
    NH, USA
    Posts
    3,149
    This sounds like a homework question.

  3. #3
    Trusted Penguin Cabhan's Avatar
    Join Date
    Jan 2005
    Location
    Seattle, WA, USA
    Posts
    3,230
    I agree that this sounds like homework, so I won't answer you directly.

    I think that you should go and research how the fork() function works. Go to your terminal and enter the command "man fork" to see a manual page that will explain everything. Hopefully this will help you understand.
    DISTRO=Arch
    Registered Linux User #388732

  4. #4
    Just Joined!
    Join Date
    May 2009
    Posts
    7
    ok, i will do it. i hope i will understand.
    but if i get any difficulty then i'll be here again.

    Thanks. I am new bee to tis Linux programming thats why i asked this question.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...