execute shell command (c)

2020-03-31 06:55发布

问题:

I this part of code, instructs my program (which make screenshots) to spawn a command and quit (close) itself. This can be used to switch to a program using a key in my program, such as to spawn "gimp" or another image editor that a user would like to use it.

case SWITCH_TO:
    if( arg ) {
        char commandline[ 256 ];
        snprintf( commandline, sizeof (commandline), "%s &", arg );
        system( commandline );
        cmd->quit = 1;
    }
    break;

For example using:

program-command SWITCH_TO "gimp"

will have my program call system( "gimp &" ), quit (close) itself and run gimp.

program-command SWITCH_TO "fotoxx"

will have my program call system( "fotoxx &" ), quit (close) itself and run fotoxx.

I want my program to check if "commandline" is valid (application found in $PATH) and if not, command "program-command SWITCH_TO" not run and not close my program ("cmd->quit = 1" do this, close program).

Thanks

回答1:

As an initial solution, you can try adding a check of the return value of the system() call.

It will be -1 on error, or else the return status of the program you run. Not sure how the latter behaves when you use & to get a child process. Also not sure if that detaches the child enough from your parent; if not, the child will terminate when you quit your application.

As others have suggested, look into fork() and exec() calls to do this properly. You can use a plain exec() to replace your process with that of the program you wish to start; if that fails you are still running, and thus you never need to set the quit flag in that case.



标签: c shell