试图在 c 中为 win32 api 创建一个简单的 shell [英] trying to create a simple shell in c for win32 api

查看:18
本文介绍了试图在 c 中为 win32 api 创建一个简单的 shell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了 msdn 文档中给出的演示代码 http://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx 我想知道你是否知道如何获取 argv[] 命令以在 CreateProcess 函数中执行...在我得到可执行文件后尝试输入 dir

I went through the demo code given in the msdn documentation http://msdn.microsoft.com/en-us/library/windows/desktop/ms682512(v=vs.85).aspx and i wanted to know if you knew how to get the argv[] command to execute in the CreateProcess function... when i try executing the file, it says create process failed when i try the following snippet and then i try to type in dir after i get the executable

 if( !CreateProcess( NULL,  
        argv[1],        
        NULL,           
        NULL,          
        FALSE,           
        0,              
        NULL,          
        NULL,           
        &pi )           
    ) 

推荐答案

Dir是cmd.exe执行的命令;不是您可以使用 CreateProcess 执行的程序.因此,要执行您想要的操作,您需要启动 cmd.exe 并在命令行上将dir"传递给它.最简单的方法是使用 system 函数.您的程序应如下所示:

Dir is a command that cmd.exe executes; not a program you can execute with CreateProcess. So to do what you want, you need to launch cmd.exe and pass "dir" on the command line to it. The simplest way to do that is with the system function. Your program should look something like this:

#include <process.h>

int main(int argc, char *argv[])
{
   system(argv[1]);
}

显然,您需要添加错误检查,但这应该可以满足您的需求.

Obviously, you need to add error checking, but this should do what you want.

这是一个使用 CreateProcess 的工作示例.请注意,/k 标志告诉 cmd.exe 在执行命令后保持打开状态.如果你想让它执行命令然后退出,把/k 改成/c.

Here is a working example using CreateProcess. Note that the /k flag tells cmd.exe to remain open after executing the command. If you want it to execute the command and then exit, change /k to /c.

#include <windows.h>

void main()
{
   STARTUPINFO si;
   PROCESS_INFORMATION pi;

   memset(&si, 0, sizeof(si));
   si.cb = sizeof(si);

   CreateProcess(NULL,  
                 "cmd.exe /k dir",
                 NULL,           
                 NULL,          
                 FALSE,           
                 CREATE_NEW_CONSOLE,              
                 NULL, 
                 NULL,         
                 &si,           
                 &pi );           
}

这篇关于试图在 c 中为 win32 api 创建一个简单的 shell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆