[英]execute shell command (c)
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.
可以使用程序中的键将其切换到程序,例如生成“ gimp”或用户想要使用的其他图像编辑器。
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. 将具有我的程序调用system(“ gimp&”),退出(关闭)自身并运行gimp。
program-command SWITCH_TO "fotoxx"
will have my program call system( "fotoxx &" ), quit (close) itself and run fotoxx. 将具有我的程序调用系统(“ fotoxx&”),本身退出(关闭)并运行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). 我希望我的程序检查“命令行”是否有效(在$ PATH中找到应用程序),否则,命令“ program-command SWITCH_TO”不运行并且不关闭我的程序(“ cmd-> quit = 1”),请关闭程序)。
Thanks 谢谢
As an initial solution, you can try adding a check of the return value of the system()
call. 作为初始解决方案,您可以尝试添加对
system()
调用的返回值的检查。
It will be -1 on error, or else the return status of the program you run. 错误时将为-1,否则将运行的程序返回状态。 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. 正如其他人所建议的那样,研究一下
fork()
和exec()
调用可以正确地做到这一点。 You can use a plain exec()
to replace your process with that of the program you wish to start; 您可以使用普通的
exec()
将进程替换为要启动的程序; if that fails you are still running, and thus you never need to set the quit flag in that case. 如果失败,则您仍在运行,因此在这种情况下,您无需设置退出标志。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.