简体   繁体   中英

Kill process by ID in argument on windows

I would like to write a program which kills process by Id. When I run it by name.exe [pid], it not working. Here is my code:

      int main(int argc, char *argv[])
    {
        DWORD pid = argv[1];
        HANDLE handleOfMyProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
        TerminateProcess(handleOfMyProcess, 5);
    }

When I don't write line

DWORD pid = argv[1];

and give pid number as third argument, for example 1243 in this way:

HANDLE handleOfMyProcess = OpenProcess(PROCESS_TERMINATE, FALSE, 1243);

it works.

My question is why the first way doesn't work ?

Because the arguments of main are strings, you cannot assign an argument directly to a DWORD ; you will have to convert it.

The definition of main shows this:

int main(int argc, char *argv[]);

You can convert it with atoi :

    DWORD pid= atoi(argv[1]);

And you must turn warnings of your compiler on because the compiler would have given you a warning

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM