GIDForums  

Go Back   GIDForums > Computer Forums > Computer Software Forum - Linux
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 16-Mar-2007, 07:26
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

How a child process past a value to parent process?


The following program need LiINUX Fedora Ajunta
to compile and RUN:

I got this question:

Write a program call Sum.c which will do the summation of 1 to n where n is an integer larger than 1, given by the user.

(a) Invoke Sum.c from the child process.
(b) Discuss the method which allows the communication between two processes.
(c) Use the method identified in (b) so that the Sum process will send the result of the summation to the parent process. The parent process then output the result.

I had done a) and b), but i need guidance for the part c)

Here's my code:

Main program:
CPP / C++ / C Code:
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>

extern int errno;

int *arg[] = {"printf","scanf",(int *)0};
#define NULL	0

int main (void) 
{

	
if (fork()) 	 			/*This is the child process */
	{
	sleep(1);
	execv("/home/Desktop/Sum",arg);	/*Execute the child process*/
	 /*	exit (0);			Should never get
here,terminate */
	 }
	 
/* parent code */
else
	{
	printf ("Parent in execution …\n");
	sleep(2);
	
	if (wait (NULL) > 0)	/*child terminating */
	printf ("Parent detects terminating child\n");
	
	sleep(2);
	}
	printf ("Parent terminating… \n");	
}


Sum.c:
CPP / C++ / C Code:
Sum.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>

extern int errno;

printf("Enter the number for summation = ");
scanf("%d",&num);	
	printf("The number entered is = %d\n", num);
while(num<2)
	{
	printf("Error. The value must greater than 1\n");
	printf("Enter the number for summation = ");		
	scanf("%d",&num);
	printf("The number entered is = %d\n", num);
	}
	
	for(i=1;i<=num;i++)
	{
	sum = sum + i;
	}

So how to return the value from sum.c into main program?
This is a C language right? I only start learning from C++, so any C code i wrote it wrong please correct me.

Thanks a lot.

Regards,
Reny
  #2  
Old 16-Mar-2007, 10:34
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: How a child process past a value to parent process?


Quote:
Originally Posted by Reny
So how to return the value from sum.c into main program?
I'll take this one first:

Since your code includes the header <shm.h>, my guess would be that you are supposed to used shared memory. There are actually several ways to effect inter-process communications.

One place to start learning is:
http://beej.us.guide. Yes, that's the same "beej" who maintains the excellent "Beej's Guide to Nework Programming". Just click on the ipc link. Among the topics covered there is a shared memory link

You might look for other explanations and sample code in places like http://linuxgazette.net/104/ramankutty.html
Quote:
Originally Posted by Reny
The following program need LiINUX Fedora Ajunta
to compile and RUN:
Maybe it compiles and runs, but I have a few problems. Mainly, your identification of the child process is wrong. (fork() returns zero if it is the child process). Is that why you had all of those hokey "sleep()" things? To make it appear to work? Or what?

Before getting into shared memory, I respectfully suggest that you make sure you understand exactly how the execv and forking stuff works.

Here are my examples for the "sum" and the "main" programs (no shared memory, yet):

CPP / C++ / C Code:
/* sum.c */
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num;

    printf("\nEnter a non-negative integer: ");
    if ((scanf("%d", &num) == 1)  && (num >= 0)){
        printf("The sum of integers from 0 up to and including %d is ", num);
        num *= (num + 1);
        num /= 2;
        printf("%d\n\n", num);
        return (EXIT_SUCCESS);
    }
    else {
        printf("That was an invalid entry\n\n");
        return (EXIT_FAILURE);
    }
}
This is the target of the child process. It doesn't know (or care) whether it was invoked from execv() of another process or just running from a command line or whatever.

Now, here is the main program: It forks a child. The child runs the target. I made it so that for test purposes you can give it the name of a target that doesn't exist as well as trying other target programs at several locations on your system. The default target is /tmp/sum.

Note use of standard library definitions for the return values. This code will be as portable as you can make it. (Note that even though the return data type is int, operating systems like Linux actually make a 16-bit value available to the calling program, and it is big-endian (!), so you must, in general, resist the temptation to use the return value of the target as a way of having the forking program get a value from the target.


Now, here is the main program:

CPP / C++ / C Code:
/* z.c: the main forking program */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>

int main(int argc, char **argv)
{
    char *target = "/tmp/sum"; /* the default argument              */
    char *arg[] = {"sum", 0};  /* null-terminated list of arguments */
    int status;

    if (argc > 1) {
        target = argv[1];
    }

    if (fork() == 0) { /* This is the forked child process */
        execv(target, arg); /* Execute the target process */
        perror(target);    /* It shouldn't return */
        exit(EXIT_FAILURE);
    }

    else { /* This is the parent process */
        int retval;
        retval = wait(&status);
        if (retval == -1) {
            perror("Uh-oh");
        }
        else {
            if (status == EXIT_SUCCESS) {
                printf("Satisfactory result from %s\n", target);
            }
            else {
                printf("Unsatisfactory result from %s\n", target);
            }
        }
    }
    return status;
}

I have deleted the ipc and shm headers for this program, and I have shown the only headers needed for my Linux installation. You should compile both programs on your system with gcc -Wall -W -pedantic to make sure you get absolutely no compiler messages of any kind before proceeding. Your exact header names and locations may differ.

Now, after putting the "sum" executable in my /tmp directory, here are a few runs of the main forking program (I called it "z"):

Code:
$ z Enter a non-negative integer: 123 The sum of integers from 0 up to and including 123 is 7626 Satisfactory result from /tmp/sum $ z Enter a non-negative integer: zzz That was an invalid entry Unsatisfactory result from /tmp/sum $ z /temp/sum /temp/sum: No such file or directory Unsatisfactory result from /temp/sum

Then, after reading about shared memory, you will be ready to rock and roll!

Regards,

Dave
  #3  
Old 16-Mar-2007, 21:36
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

Re: How a child process past a value to parent process?


thx dave, i owe you a lot, now i need a lot of time to swallow it.
  #4  
Old 05-Apr-2007, 09:43
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

Re: How a child process past a value to parent process?


Dave, i'll like to give some of my feedback to you:

1) ya, i did hand up of assignment, but i got a very bad viva, and a bad result.

2) i check bec my problems, and i found that i'm totally dun understand the C language and of course the share memory segment.

3) yes, i'm not talented in this field, as always.

4) Finally i had chosen not to skip this problem, and hopefully you're kind enough to reguide me again.

The following i'll post you the full version of my assignment
  #5  
Old 05-Apr-2007, 09:46
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

Re: How a child process past a value to parent process?


2. (a) Program Assign2.c is a skeleton of a mini shell. A mini shell is a program which waits for the command from the user and execute the command.

(i) Compile and run Assign2.c and Test.c. Insert a system call in the if statement which will create a child process. Use a system call which will display the process id of the child, and also the parent. Include in your report.
(ii) Once the child process is successfully created, it should then execute the executable of Test.c. Insert the appropriate system call to enable this.
(iii) Execute the ls command from your mini shell. Copy and paste the output into your report. Explain what happen.




3. Write a program call Sum.c which will do the summation of 1 to n where n is an integer larger than 1, given by the user.

(a) Invoke Sum.c from the child process.
(b) Discuss the method which allows the communication between two processes.
(c) Use the method identified in (b) so that the Sum process will send the result of the summation to the parent process. The parent process then output the result.



These are the example code my lecture gave us:
Assign2.c
CPP / C++ / C Code:
#include <sys/wait.h>
#define NULL	0

int main (void) {
	/* if (____________________) {		This is the child process */
	/*    ____________________;		Execute the child process */
	/*	exit (0);				Should never get here, terminate */
/*} */

/* parent code */
	printf (“Parent in execution …\n”);
	sleep (2);
	if (wait (NULL) > 0))	/*child terminating */
printf (“Parent detects terminating child\n”);
	printf (“Parent terminating… \n”);
}


Test.c
CPP / C++ / C Code:
int main (void) {
printf (“Child in execution… \n”);
sleep (1);
printf (“Child terminating… \n”);
}
  #6  
Old 05-Apr-2007, 09:51
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

Re: How a child process past a value to parent process?


And Also, I had read through the guidance you gave me for the shared memory segment, ya...those 0644, "arg" at the execv...not understand it's function.

So, i'll try to read again and again, hopefully wont be feeded so much.
  #7  
Old 05-Apr-2007, 11:26
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: How a child process past a value to parent process?


Quote:
Originally Posted by Reny
"arg" at the execv...not understand it's function.

The "arg" of the execv function is like the argv in main:

CPP / C++ / C Code:
int main(int argc, char *argv[])

Or, its exact equivalent:

CPP / C++ / C Code:
int main(int argc, char **argv)

So argv is an array of pointers to char. Each item pointed to is a C-style "string": a null-terminated sequence of chars in memory. The final pointer value is NULL (So argv is a NULL-terminated sequence of pointers.)

If you want to call your child process with arguments, then you put the arguments into an array and use the array name as the second argument to execv. According to the C standard, you don't have to supply any arguments (and the child process may or may not use them even if you do supply them)


So in general for a child process named "test", in the current directory, If you want to pass an argument:

CPP / C++ / C Code:
char *target = "./test";
char *arg[3] = {"./test",            /* The name of the child program       */
                "argument_number_1", /* The command-line argument to target */
                NULL                 /* a NULL after the last argument      */
               };
.
.
.
        execv(target, arg);
.
.
.

If you don't want to pass any arguments to the child, you could do someting like:

CPP / C++ / C Code:
char *target = "./test";
char *arg[2] = {"./test",            /* The name of the child program       */
                NULL                 /* No command-line arguments           */
               };
.
.
.
        execv(target, arg);
.
.

Or even:

CPP / C++ / C Code:
char *target = "./test";
char *arg[1] = {NULL};
.
.
.
        execv(target, arg);
.
.
.

Regards,

Dave
Last edited by davekw7x : 05-Apr-2007 at 12:40.
  #8  
Old 07-Apr-2007, 09:20
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

Re: How a child process past a value to parent process?


Yes, i got it, what's the use of command line?

and y we must pass 2 char pointers into execv? What would happen if i pass *target into execv only?

thx for your patience.
  #9  
Old 07-Apr-2007, 09:22
Reny's Avatar
Reny Reny is offline
Junior Member
 
Join Date: Aug 2006
Posts: 60
Reny is on a distinguished road

Re: How a child process past a value to parent process?


oh ,is the command line exactly the word we going to type in for a terminal to execute our command?
  #10  
Old 07-Apr-2007, 14:41
davekw7x davekw7x is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Left Coast, USA
Posts: 5,305
davekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to beholddavekw7x is a splendid one to behold

Re: How a child process past a value to parent process?


Quote:
Originally Posted by Reny
oh ,is the command line exactly the word we going to type in for a terminal to execute our command?

Yes.

Regards,

Dave
 
 

Recent GIDBlogNot selected for officer school by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
problem with spawnl() and system() balajiramani C Programming Language 3 25-Jan-2007 07:49
Program on creating a process!! sac_garg C Programming Language 3 01-Oct-2006 09:22
[TUTORIAL] Calling an external program in C (Linux) dsmith C Programming Language 4 22-Apr-2005 13:30
apache php no longer working (MX??) XP?? ChicoMendez Apache Web Server Forum 5 30-Aug-2004 10:51
Assign label to child process? 7eleven C++ Forum 0 31-May-2004 21:43

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 14:57.


vBulletin, Copyright © 2000 - 2010, Jelsoft Enterprises Ltd.