Thread: returning value to parent and printing.

  1. #1
    Registered User
    Join Date
    Jun 2008
    Posts
    8

    returning value to parent and printing.

    hi im quiet new to c programing so i wonderd if i could get some help on this code

    Code:
    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    
    int Child(int z);
    int Parent(int y);
    
    int main()
    {
    	int x;                                   /* pid storage for later use*/
    	int z;	                                 /*returned pid value*/
    	int y;					/*returned pid value*/
    	x = getpid();        				/* insert parent id into x for later use */
    	printf("First pid is %d\n", x); 	 	 /* shows id of verry first proccess */
    	pid_t pid;
    	pid = fork();
    	if (pid == 0)
    		Child(z);
    	else
    		Parent(y);
    	pid = wait();
    	printf("FirstP, Child pid is %d\n", z); 
    	printf("FirstP, Parent pid is %d\n", y);
    
    }
    
    int Child(int z)
    {
    	
    	z = getpid();					/*stores pid to be returned*/
    	printf("child pid is %d\n", getpid());
    	return z;
    }
    
    int Parent(int y)
    {
    	
    	y = getpid();					/*stores pid to be returned*/
    	printf("parent pid is %d\n", getpid());
    	return y;
    }
    i cant get " z and y" to print out the correct pid from the Child() and Parent() function when returned to main. could someone tell me what im missing here?

    this is what it throws out after being run

    Code:
    First pid is 6233
    parent pid is 6233
    child pid is 6234
    FirstP, Child pid is 134514025
    FirstP, Parent pid is -1076644744
    FirstP, Child pid is 134514025
    FirstP, Parent pid is -1076644744

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    As soon as you call fork(), the x, y, z variables are separate instances in the parent and child processes. So changing one of them has no effect on the other.

    You can get a small (<256) integer out of the child, by doing
    exit(smallInteger);

    And you can recover that small integer by using waitpid() in the parent (see manual page for details).

    If you've got anything more complicated than that, then you need another plan, such as
    - pipes
    - the file system
    - shared memory
    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. SIGNAL Suspended?
    By Victor_November in forum C Programming
    Replies: 11
    Last Post: 11-10-2009, 11:55 PM
  2. Why isn't the execlp() function doing anything?
    By jsrig88 in forum C Programming
    Replies: 5
    Last Post: 10-12-2009, 10:09 AM