21xrx.com
2024-09-20 00:18:48 Friday
登录
文章检索 我的文章 写文章
C++如何创建进程?
2023-06-30 15:30:13 深夜i     --     --
C++ 创建进程 进程管理 多进程编程 进程调度

C++是一种功能强大的编程语言,可以用来编写各种类型的应用程序。其中一个常见的任务是创建进程。

创建进程是操作系统中的一个非常重要的概念。当您需要在同一个程序中运行多个任务或应用程序时,您需要创建进程。C++可以使用多种方法来创建进程。下面是一些示例。

一种创建进程的方法是使用Windows API。Windows API是一组可用于Windows操作系统的函数和操作。以下是一个使用CreateProcess函数的示例代码片段:


#include <windows.h>

#include <stdio.h>

int main()

{

STARTUPINFO si;

PROCESS_INFORMATION pi;

ZeroMemory( &si, sizeof(si) );

si.cb = sizeof(si);

ZeroMemory( &pi, sizeof(pi) );

// Create the child process

if( !CreateProcess( NULL,  // No module name (use command line)

"notepad.exe", // Command line

NULL,      // Process handle not inheritable

NULL,      // Thread handle not inheritable

FALSE,     // Set handle inheritance to FALSE

0,       // No creation flags

NULL,      // Use parent's environment block

NULL,      // Use parent's starting directory

&si,      // Pointer to STARTUPINFO structure

&pi )      // Pointer to PROCESS_INFORMATION structure

)

{

printf( "CreateProcess failed (%d).\n", GetLastError() );

return 1;

}

// Wait until child process exits.

WaitForSingleObject( pi.hProcess, INFINITE );

// Close process and thread handles.

CloseHandle( pi.hProcess );

CloseHandle( pi.hThread );

return 0;

}

在上面的代码中,CreateProcess函数用于创建一个新的进程,此处使用的是notepad.exe进程(也就是记事本)。WaitForSingleObject函数用于等待进程完成。最后,CloseHandle函数用于清理临时句柄。

另一种创建进程的方法是使用fork()函数。fork()函数是UNIX操作系统上的一种函数,用于创建一个新的进程。以下是一个使用fork()函数的示例代码片段:


#include <unistd.h>

#include <stdio.h>

int main()

{

pid_t pid;

/* create a new process */

pid = fork();

if (pid == -1)

{

/* error occurred */

fprintf(stderr, "Fork Failed");

return 1;

}

else if (pid == 0)

{

/* child process */

execlp("/bin/ls", "ls", NULL);

}

else

{

/* parent process */

/* parent will wait for the child to complete */

wait(NULL);

printf("Child Complete");

}

return 0;

}

在上面的代码中,fork()函数用于创建一个新的进程。在子进程中,使用execlp函数来执行新的程序(在这个例子中是/bin/ls)。在父进程中,使用wait()函数等待子进程完成。

总结起来,使用C++可以很容易地创建新的进程。您可以使用Windows API或UNIX系统调用中的函数来创建进程并执行不同的任务。掌握这些基本概念是C++编程的关键,可以使您的代码更加灵活和强大。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复