Spawned Program Accessing Parent's FunctionsLast reviewed: July 17, 1997Article ID: Q43318 |
5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a | 1.00 1.50
MS-DOS | OS/2 | WINDOWSkbprg The information in this article applies to:
SUMMARYA program spawned with the P_WAIT modeflag can successfully call functions within its parent. The functions must be set up in such a way, however, that CPU registers are preserved and the data segment register is loaded as necessary. It is also very important that all necessary startup code and C run time library routines are present whenever the parent functions are called. Warning: This procedure is neither recommended nor supported. This article is for informational purposes only.
MORE INFORMATIONThe programs below, PARENT.C and CHILD.C, demonstrate this technique. This method of sharing functions may be useful as a primitive form of overlaying when there is a need for a common set of functions to be accessed by a sequence of spawned child processes. The method of communication from the parent to the child is through command-line arguments. In the parent, a far pointer to the function that will be called is converted to a string and passed as a parameter through a spawn. In the child, it is then converted back into a far pointer. There are several considerations to be made when writing code of this nature:
Sample Code:The following is the parent program:
/* * PARENT.C */ #include <stdio.h> #include <stdlib.h> #include <process.h> int far _saveregs _loadds myfunc(void); void main(void); int k = 0, l = 0; /* Globals to be accessed inside myfunc */ int far _saveregs _loadds myfunc(void){ int i, /* Return value */ j; /* Indexing */ for (j = 1; j < 10; j++) { k = k + j; l = k * j; } i = k + l; return (i);}
void main(){ int (far _saveregs _loadds * myfuncaddr) (void); /* myfunc() pointer */ char address[16]; /* address topass */
printf("Now inside parent main().\n"); myfuncaddr = (int (far _saveregs _loadds *) (void)) myfunc; ultoa((unsigned long) myfuncaddr, address, 10); printf("Address of myfunc(): %s\n", address); spawnlp(P_WAIT, "child.exe", "child.exe", address, NULL); printf("Back inside parent main().\n");}
The following is the child program:
/* * CHILD.C */ #include <stdio.h> #include <stdlib.h> void main(int argc, char **argv){ int (far _loadds _saveregs * myfuncaddr)(void); /* Pointer to parent's function */ int i; /* Function return value */ printf(" Now in child.\n"); myfuncaddr = (int (far _loadds _saveregs *)(void))atol(argv[1]); printf(" Received: %ld\n", myfuncaddr); printf(" Calling myfunc().\n"); i = myfuncaddr(); printf(" Result of myfunc(): %d\n", i); printf(" Leaving child.\n"); } |
Additional reference words: kbinf 6.00 6.00a 6.00ax 7.00 1.00 1.50
© 1998 Microsoft Corporation. All rights reserved. Terms of Use. |