在C语言中,我们可以使用操作系统提供的API来创建、管理和控制进程,以下是一些常用的C API及其功能:
(图片来源网络,侵删)1、fork() 创建一个新的进程
2、exec() 在新进程中执行新的程序
3、wait() 等待子进程结束
4、getpid() 获取当前进程的ID
5、getppid() 获取父进程的ID
6、exit() 结束当前进程
7、kill() 向进程发送信号
下面是一个简单的示例,展示了如何使用这些API:
#include#include #include #include #include int main() { pid_t pid = fork(); // 创建一个新的进程 if (pid < 0) { printf("fork failed "); exit(1); } if (pid == 0) { // 子进程 printf("This is the child process, PID: %d ", getpid()); sleep(2); // 模拟子进程执行任务 exit(0); } else { // 父进程 int status; printf("This is the parent process, PID: %d ", getpid()); printf("Waiting for the child process to finish... "); wait(&status); // 等待子进程结束 printf("Child process finished with status: %d ", WEXITSTATUS(status)); } return 0; }
在这个示例中,我们首先使用fork()创建一个新进程,然后根据fork()的返回值判断当前进程是父进程还是子进程,子进程打印其PID并等待2秒后退出,而父进程则等待子进程结束并打印子进程的退出状态。