-   Programming (
-   -   Help with Spawning a process - passing arguments (

Kenhokie 04-03-2009 02:29 PM

Help with Spawning a process - passing arguments
I am trying to spawn a new process and pass arguments to that newly spawned process. I am using the call: posix_spawn(..,..,..) I can get the spawned process to run, however I am having trouble passing the arguments correctly. It must be a argument pointer problem. Any ideas. Is there another easier way to spawn a process. (not fork() or threads).

Heres what I have:


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <spawn.h>

//  Main process

int main(void){

        pid_t pid;

        char* myArgv[10];

        char arg1[16];
        char arg2[16];
        char arg3[16];
        int retVal;

        //  Create 3 arguments to pass
        sprintf(arg1, "%d", 4);
        sprintf(arg2, "%s", "My string");
        sprintf(arg3, "%d", 350);

        myArgv[1] = arg1;
        myArgv[2] = arg2;
        myArgv[3] = arg3;

        //  Spawn "helloWorld with args"
        retVal = posix_spawn( &pid, "helloWorld",
                              NULL, NULL,
                              myArgv, NULL );

        printf("Here is the main process:  Ending\n");

        return 0;

//  HelloWorld process

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <spawn.h>

int main (int argc, char **argv) {
    printf(" HelloWorld argc = %d \n", argc);
    printf(" argv0 = %s \n", *(argv+0));
    printf(" argv1 = %s \n", *(argv+1));
    printf(" argv2 = %s \n", *(argv+2));
    printf(" argv3 = %s \n", *(argv+3));

    printf(" HelloWorld end. \n");
    return 0;

}  // end main()

Here's what my output looks like:

HelloWorld argc = 0
0 = (null)
1 = (null)
Here is the main process: Ending

Can anybody help me? Thanks in advance...

running on Fedora 9

raconteur 04-03-2009 02:51 PM

I suspect your argv array isn't properly terminated. Initialize all of the members to null before assigning values to them and posix_spawn should then pass them correctly to the spawned process (the last entry will be null terminated, followed by another null, which is what argv requires).

edit: in addition, your argv[0] also needs to be initialized. Under normal circumstances this is filled in by the framework but posix_spawn appears to want to be told.
When I did that, the program behaved as expected.

All times are GMT -5. The time now is 09:34 AM.