Search code examples
cwindowsconsole-applicationspawncreateprocess

How to start an independent program(in a separate console window) from another program in C on Windows?


I have a C application on Windows which needs to launch another application on some condition. I have been able to successfully launch the other application using the following line of code but the first application (the parent) and the new application (the child) are using the same window. I want them to have separate windows. How do I do it?

My code for launching the child application is:

    char *app_path = "path\\my_app.exe";
    char *app_arg = "arg";
    if (-1 == _spawnl(P_NOWAITO, app_path,app_arg,NULL))
    {
        printf_s("\nUnable to start the app. Error code %d", errno);
    }
    else
    {
        printf_s("\App started successfully.");
    }

N.B: the child app is not really a child app except for it being started by the "parent".


Solution

  • You can start your program like this:

    char *cmd_args = "/C C:\\Users\\Administrator\\Desktop\\my_app.exe app_arg";
    
    if (-1 == _spawnl(P_NOWAITO, "C:\\Windows\\System32\\cmd.exe", cmd_args,NULL))
    {
        printf_s("\nUnable to start the app. Error code %d", errno);
    }
    else
    {
        printf_s("\App started successfully.");
    }
    

    start is a cmd-builtin, which will start the following command in a new window.